【发布时间】:2020-06-29 16:37:03
【问题描述】:
我正在使用 ajax 从 javascript 前端发布数据以表达 js 有后端服务器。我如何在 express js api 方法 req 参数中获取发布的数据。当我尝试解析以下请求数据时遇到问题是我的代码。请帮我解决这个问题
$.ajax({
url: "http://localhost:8080/api/save_user/",
type: "POST",
crossDomain: true,
data: { name: 'Justin', number: '662***' },
dataType: "json",
contentType: "application/json",
success: function (response) {
var resp = JSON.parse(response)
},
error: function (xhr, status) {
alert("error");
}
});
Express Js服务器端
const express = require('express');
const path = require('path')
const os = require('os');
const app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())
//deploy the smart contract
app.post('/api/save_user', (req, res) => {
console.log((JSON.parse(req.body)));
res.send({})
})
错误日志
SyntaxError: Unexpected token n in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/node_modules/body-parser/lib/types/json.js:158:10)
at parse (/node_modules/body-parser/lib/types/json.js:83:15)
at /node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/raw-body/index.js:224:16)
【问题讨论】:
-
log.console(response)的输出是什么 -
在路由
app.use(express.json({ type: ['application/json', 'text/plain'] }))之前在express中添加行并重试 -
我面临问题 console.log((JSON.parse(req.body)));在服务器端 express js
标签: javascript node.js express