【问题标题】:Express routing post call unexpected token in json快速路由后调用json中的意外令牌
【发布时间】:2018-08-22 06:05:27
【问题描述】:

我需要一些帮助来处理我在 Express 中的路由、发出呼叫以及检索 postrequest 中的数据。

我尝试通过记录 req.body 来检索数据,但返回 {},我尝试将 bodyParser 添加到我的 App.js 中,当我进行 post 调用时出现以下错误:

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!'))

routes/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)
                 }
        });
}

【问题讨论】:

    标签: json express post routes


    【解决方案1】:

    你可以用Postman来测试路由吗?确保选择 x-www-form-urlencoded 作为正文格式,因为您使用的是 bodyparser.urlencoded({ extended: true })

    【讨论】:

    • 我发布了一张邮递员的图片。如你所说的身体,键'test',值'test'
    • 看看this。如果有帮助,请告诉我们。
    • 有效,我将更改该代码:) 谢谢。我不确定我的有什么问题。也许数据帖子中需要 json.stringify。
    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 2018-11-16
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多