[英]How to POST API as an object instead of array
How can I post the data as a object如何将数据发布为 object
I tried to make this code but it gives me errors我试图制作这段代码,但它给了我错误
This is the code of the server:这是服务器的代码:
const projectData = [];
/* The rest of code is for setting up the server */
// GET route
app.get('/all', sendData);
function sendData(req, res) {
res.send(projectData[projectData.length - 1]);
};
// POST route
app.post('/addWeather', addWeather);
//create add Weather function
function addWeather(req, res) {
const temporary_object = {}
temporary_object.date = req.body.date;
temporary_object.temperature = req.body.temperature;
temporary_object.content = req.body.content;
projectData.push(temporary_object);
res.send(projectData[projectData.length - 1]);
}
So how can I change from this:那么我该如何改变:
const projectData = [];
To this:对此:
const projectData = {};
Without any errors没有任何错误
You can do it like this:你可以这样做:
function addWeather(req, res) {
const objectToSend = {}
objectToSend.date = req.body.date;
objectToSend.temperature = req.body.temperature;
objectToSend.content = req.body.content;
res.send(objectToSend);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.