Javascript POST请求-不使用节点和Express
我刚刚开始学习一个简单的项目的Node和Express,但由于某些原因,我无法将其发布到工作中。我的浏览器给我一个错误:无法发布/ 在此问题上的任何协助都将不胜感激。多谢各位 我的代码如下:Javascript POST请求-不使用节点和Express,javascript,node.js,express,post,Javascript,Node.js,Express,Post,我刚刚开始学习一个简单的项目的Node和Express,但由于某些原因,我无法将其发布到工作中。我的浏览器给我一个错误:无法发布/ 在此问题上的任何协助都将不胜感激。多谢各位 我的代码如下: let express = require("express") let ourApp = express() ourApp.use(express.urlencoded({ extended: false })) ourApp.get("/", function(req, res) { res.
let express = require("express")
let ourApp = express()
ourApp.use(express.urlencoded({ extended: false }))
ourApp.get("/", function(req, res) {
res.send(`
<form action='/' method='POST'>
<h2>What color is the sky on a clear and sunny day?</h2>
<input name="skyColor" autocomplete="off">
<button>Submit Answer</button>
</form>
`)
})
ourApp.post("/answer", function(req, res) {
if (req.body.skyColor.toUpperCase() == "BLUE") {
res.send(`
<p>Congrats, that is the correct answer.</p>
<a href="/">Back to homepage</a>
`)
} else {
res.send(`
<p>Sorry, that is incorrect.</p>
<a href="/">Back to homepage</a>
`)
}
})
ourApp.get("/answer", function(req, res) {
res.send("Are you lost there is nothing to see here.")
})
ourApp.listen(3000)
let express=要求(“express”)
让我们使用ourApp=express()
use(express.urlencoded({extended:false}))
ourApp.get(“/”,函数(req,res){
res.send(`
晴朗阳光下的天空是什么颜色的?
提交答案
`)
})
ourApp.post(“/answer”),函数(请求、回复){
如果(请求body.skyColor.toUpperCase()=“蓝色”){
res.send(`
恭喜,这是正确的答案
`)
}否则{
res.send(`
对不起,那是不正确的
`)
}
})
ourApp.get(“/answer”),函数(req,res){
res.send(“你迷路了吗?这里什么都看不见。”)
})
我们的应用程序。听(3000)
您遇到了错误的端点。
例如,你应该发到
还有一件事,若要在body中传递JSON数据,需要使用body解析器中间件。
对于“/”
路线,您返回的表单应具有action=“/answer”
,而不是action=“/”
你的其他路线应该保持不变,并且非常确定这会起作用
ourApp.get("/", function(req, res) {
res.send(`
<form action='/answer' method='POST'>
<h2>What color is the sky on a clear and sunny day?</h2>
<input name="skyColor" autocomplete="off">
<button>Submit Answer</button>
</form>
`)
})
ourApp.get(“/”,函数(req,res){
res.send(`
晴朗阳光下的天空是什么颜色的?
提交答案
`)
})
您的表单操作
应该是/answer
,而不是/
哦,天哪。我觉得自己是个十足的傻瓜,应该在发帖前尝试一下“/answer”。很抱歉。谢谢大家。express.json()
不适合这种POST请求。OP需要express.urlencoded()
,这是他们已经编辑过的我的答案。您认为OP想要解析JSON的原因是什么?他们已经有了一个合适的带有ourApp.use(express.urlencoded({extended:false}))
@phil是的,我看到我说的只是万一你想使用它,你可以使用它。express现在有了自己的JSON主体解析器,没有必要包括body parser
是吗,谢谢,我没有意识到它附带了自己的主体解析器。