我需要帮助我在Express中使用路由并进行后期调用,并在postrequest中检索数据。
我尝试通过登录req.body来检索数据,但是返回{},我尝试将bodyParser添加到我的App.js中,当我拨打电话时会出现以下错误:
POST http://localhost:3000/enquete/test/ 400(错误请求)
SyntaxError: Unexpected token # in JSON at position 0
这是我的代码:
App.js
const express = require('express')
const app = express()
var MongoClient = require('mongodb').MongoClient
, co = require('co')
, assert = require('assert')
, bodyParser = require('body-parser');
var indexRouter = require('./routes/index.js');
var enqueteRouter = require('./routes/enquete.js');
// 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.set('view engine', 'pug');
app.use('/', indexRouter);
app.use('/enquete', enqueteRouter);
app.use(express.static(__dirname + '/routes'));
app.use(express.static(__dirname + '/public'));
app.listen(3000, () => console.log('Example app listening on port 3000!'))
路由/ enquete.js
const express = require('express')
var router = express.Router()
router.post('/test/', function(req,res,next){
console.log('request:',req.body);
res.send('hello');
})
module.exports = router;
调用Ajax
function save(array){
$.ajax({
type: 'POST',
data: { name: "Test", location: "TestUSA" },
contentType: 'application/json',
url: 'http://localhost:3000/enquete/test/',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
},
error: function(error) {
console.log('error:', error)
}
});
}
答案 0 :(得分:1)
您可以使用Postman来测试路线吗?由于您使用x-www-form-urlencoded
bodyparser.urlencoded({ extended: true })
作为正文格式