[英]POST body not sending through cURL using JSON
I am trying to use Postman to send POST messages to my application.我正在尝试使用 Postman 将 POST 消息发送到我的应用程序。 When sending the POST message, I receive an HTTP 200 code.发送 POST 消息时,我收到一个 HTTP 200 代码。 In the response, I only get my incremented id, and not the JSON object I send.在响应中,我只得到递增的 id,而不是我发送的 JSON 对象。
When I try to use cURL from the CMD prompt, I get an error.当我尝试在 CMD 提示符下使用 cURL 时,出现错误。
I am using Node and Express for my application我正在为我的应用程序使用 Node 和 Express
Here is my application and POST method这是我的应用程序和 POST 方法
const express = require('express');
const Joi = require('joi');
const app = express();
app.use(express.json({extended: false}));
// POST
app.post('/api/courses', (req, res) => {
const {error} = validateCourse(req.body);
if(error){
return res.status(400).send(error.details[0].message);
}
const course = {
id: (courses.length + 1),
name: req.params.name
};
courses.push(course);
res.send(course);
});
// validateCourse method
function validateCourse(course){
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(course, schema);
}
Postman enter image description here邮递员在此处输入图片描述
POST headers enter image description here POST 标头在此处输入图像描述
Application after several POST messages多个 POST 消息后的应用程序
Use this用这个
const course = {
id: (courses.length + 1),
name: req.body.name
};
Your main problem is that your route accepts no route parameters but you are trying to use req.params.name
.您的主要问题是您的路线不接受任何路线参数,但您正在尝试使用req.params.name
。
Your data is in req.body
您的数据在req.body
const course = {
...req.body,
id: courses.length + 1
};
To send the equivalent request with curl, use this要使用 curl 发送等效请求,请使用此
curl \
-H "content-type: application/json" \
-d '{"name":"abcde"}' \
"http://localhost:3000/api/courses"
FYI, the express.json() middleware doesn't have an extended
option仅供参考, express.json()中间件没有extended
选项
app.use(express.json());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.