不要在节点 js rest web 中获取请求正文 api
dont get request body in node js rest web api
以下是我的nodejs代码
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response) {
console.log(request.body);
console.log('post hit');
response.json({
message: 'Post Hit'
});
});
app.listen(process.env.PORT || 8000);
以下是我的 javascript 调用上述 post 端点的代码
$.ajax({
type: "POST",
crossDomain: "true",
url: "http://localhost:8000/",
data: {
"a": "b"
},
headers: {
"Content-Type": "application/json"
},
success: function(d) {
alert(d);
console.log(d);
},
error: function(e) {
console.log(e);
alert(e);
}
});
我总是在节点 js 中得到我的 request.body 空。
有时候,rest 端点甚至都没有命中。
我不知道这是怎么回事。
在 express.js 中启用 CORS
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'X-Requested-With')
res.header('Access-Control-Allow-Headers', 'Content-Type')
next()
})
您还需要将 json 中的数据转换为 ajax。
data: JSON.stringify({
"a": "b"
})
PS :当您使用 POSTMAN 进行测试时。它不发送预检请求。这就是为什么它将在 POSTMAN 中工作的原因。
在此处阅读有关预检的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
您还可以在 chrome 中添加 "Allow-Control-Allow-Origin" 扩展名以在本地 运行 获取它。
和
data: JSON.stringify({
"a": "b"
})
在客户端发送数据。
您可以使用 this 节点模块轻松启用 cors!
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
/* other routes here */
以下是我的nodejs代码
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response) {
console.log(request.body);
console.log('post hit');
response.json({
message: 'Post Hit'
});
});
app.listen(process.env.PORT || 8000);
以下是我的 javascript 调用上述 post 端点的代码
$.ajax({
type: "POST",
crossDomain: "true",
url: "http://localhost:8000/",
data: {
"a": "b"
},
headers: {
"Content-Type": "application/json"
},
success: function(d) {
alert(d);
console.log(d);
},
error: function(e) {
console.log(e);
alert(e);
}
});
我总是在节点 js 中得到我的 request.body 空。
有时候,rest 端点甚至都没有命中。
我不知道这是怎么回事。
在 express.js 中启用 CORS
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'X-Requested-With')
res.header('Access-Control-Allow-Headers', 'Content-Type')
next()
})
您还需要将 json 中的数据转换为 ajax。
data: JSON.stringify({
"a": "b"
})
PS :当您使用 POSTMAN 进行测试时。它不发送预检请求。这就是为什么它将在 POSTMAN 中工作的原因。
在此处阅读有关预检的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
您还可以在 chrome 中添加 "Allow-Control-Allow-Origin" 扩展名以在本地 运行 获取它。 和
data: JSON.stringify({
"a": "b"
})
在客户端发送数据。
您可以使用 this 节点模块轻松启用 cors!
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
/* other routes here */