[英]when call router.post method from url get error 404 not found in express.js
我在使用 Express 时遇到问题,我正在尝试使用 app.post() 函数但它不起作用,我不知道为什么...
即使我已经包含了 bodyParser() ......
它返回 404 页面未找到错误
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var router = express.Router();
router.post("/hello",(req, res) => {
res.send('POST CALL');
});
/* GET home page. */
router.get('/', function(req, res, next) {
MongoClient.connect('mongodb://localhost:27017/nicky', function (err, client) {
if (err) throw err
var db = client.db('nicky')
db.collection('student').find().toArray(function (err, result) {
if (err) throw err
res.send(JSON.stringify(result));
})
})
});
module.exports = router;
GET 工作正常,但 POST 不正常。
也许你还没有要求和初始化 body-parser! 如果您已包含此内容,只需确认一次:
const bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
可能你忘记使用 app.use('/',require('import route here')); 在主应用程序中。
我不确定你的其余代码看起来如何,但我已经复制了你提供的代码片段,它是这样工作的:
快递post.js:
const express = require('express');
const router = express.Router();
// curl -X POST http://localhost:3000/bar/hello
router.post("/hello",(req, res) => {
res.send('It is POST');
});
// curl -X GET http://localhost:3000/bar/hi
router.get('/hi', function(req, res, next) {
res.send('It is GET');
});
module.exports = router;
express-post-server.js:
const express = require('express');
const bar = require('./express-post');
const app = express();
// curl -X GET http://localhost:3000/foo
app.get('/foo', function (req, res, next) {
res.send('This is foo GET!');
});
// register
app.use('/bar', bar);
app.listen(3000);
对于完整的运行示例,克隆node-cheat并运行 node express-post。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.