简体   繁体   中英

How to POST API as an object instead of array

Hello

How can I post the data as a 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM