我正在使用带有电子邮件和密码的JSON数据从Postman发出POST请求,但是当我试图在Postman的响应窗口中显示该消息时,它什么也没显示。
似乎POST请求未随请求发送JSON数据,否则在访问请求数据时我可能出了点问题。
这是我的代码:
const express = require("express");
const app = express();
const database = {
users: [
{
id: "1234",
name: "john",
email: "john@gmail.com",
password: "john",
entries: 0,
joined: new Date()
},
{
id: "123",
name: "sally",
email: "sally@gmail.com",
password: "sally",
entries: 0,
joined: new Date()
}
]
};
app.get("/", (req, res) => {
res.send("This is working Get");
});
app.post("/signin", (req, res) => {
res.json(req.body);
});
app.listen(3000, () => {
console.log("Server Started at port number 3000");
});
答案 0 :(得分:2)
第1步:
如果您使用raw(application/json)
进行请求,则需要在npm下安装该应用,以解析您的请求数据,
npm install body-parser --save
请检查下面的链接以获取更多信息:
https://www.npmjs.com/package/body-parser
第2步::您需要在服务器文件中添加以下行
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json())
第3步::集成bodyParser
后,您可以使用req.body
您在这里用解决方案进行编码:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
const database = {
users: [{
id: "1234",
name: "john",
email: "john@gmail.com",
password: "john",
entries: 0,
joined: new Date()
},
{
id: "123",
name: "sally",
email: "sally@gmail.com",
password: "sally",
entries: 0,
joined: new Date()
}
]
};
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json())
app.post("/signin", (req, res) => {
res.json(req.body);
});
app.listen(8080, () => {
console.log("Server has been started");
});
答案 1 :(得分:1)
与express一起,您需要'body-parser'模块才能执行邮寄请求,
const express = require("express");
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.raw());
const database = {
users: [
{
id: "1234",
name: "john",
email: "john@gmail.com",
password: "john",
entries: 0,
joined: new Date()
},
{
id: "123",
name: "sally",
email: "sally@gmail.com",
password: "sally",
entries: 0,
joined: new Date()
}
]
};
app.get("/", (req, res) => {
res.send("This is working Get");
});
app.post("/signin", (req, res) => {
res.json(req.body);
});
app.listen(3000, () => {
console.log("Server Started at port number 3000");
});