gpt4 book ai didi

javascript - Express .post 路由方法未定义

转载 作者:太空宇宙 更新时间:2023-11-04 00:26:30 25 4
gpt4 key购买 nike

我是 Nodejs 和 Express 的新手,我似乎无法想象为什么这个方法在 Webstorm 中没有得到解决。 .get 方法返回正常,使用 .all 方法测试它也正常。我不知道为什么 .post 方法未解析, Node 启动正常,但如果我尝试通过 Postman 向它发送 post 请求,它只会给出错误:

the Postman error

app.js

'use strict';

var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var routes = require("./routes");

app.use(function (req, res, next) {
console.log(`${req.method} ${req.originalUrl}`);
next();
});

app.use(bodyParser.json());

app.use("/questions", routes);
// routes(app);

var port = process.env.PORT || 3000;

app.listen(port, function () {
console.log("Express is running at", port);
});

routes.js

'use strict';

var express = require("express");
var router = express.Router();

// GET /questions
// Route for getting all questions
router.get("/", function (req, res) {
res.json({
response: "You sent me an awesome GET request, thank you!"
});
});

// POST /questions
// Route for creating a question
router.post("/questions", function (req, res) {
res.json({
response: "You sent me an awesome POST request, thank you!"
});
body: req.body;
});

module.exports = router;

package.json

{
"name": "02-express-api",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.13.4"
}
}

最佳答案

router.post("/questions", 应该是 router.post("/", 才能正常工作;现在,该处理程序正在响应 URI /questions/questions,因为路由器本身已附加到 /questions 下的句柄 URI。

关于javascript - Express .post 路由方法未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42586838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com