简体   繁体   中英

Cannot insert json record using axios POST with node.js into postgresql database?

I've tried googling tutorials/examples but I cannot find anything. Currently, I can insert the JSON record into the first column so I know everything is plugged in, but the JSON is not being broken apart and being put into their respective columns.

This is what I have on my client making the call with a POST

async function apiAddRecordToTable(record, table_name) {
   params = record;
   let res = await axios.post('http://localhost:3000/tables/addrecord/' + table_name, params);
   console.log('add record api called with selected tablename: ' + table_name);
   console.log(res.data);
}

This is what I am calling it with (just to test)

apiAddRecordToTable({
   "user_id" : "110",
   "user_lon" : "64",
   "user_lat" : "-111",
}, 'user');

As for the server, I have a

app.post('/tables/addrecord/user', db.addRecordUser);

and that calls into this final function:

function addRecordUser(request, response) {
   console.log('into final add record user method');
   console.log(request);
   const rec = request.body;
   pool.query('INSERT INTO user_table VALUES ($1)', [rec], (error, results) => {
      if (error) {
         throw error
      }
      console.log(results);
      response.status(201).send('Row added')
   })
}

The final result in the table looks like

USER ID |  USER_LON | USER_LAT
{"user_id":"110","user_lon":"64","user_lat":"-111"}, <null>, <null>

I understand that it's most likely inserting the entire record because of the $1 argument but I tried so many variations and searched on how json gets inserted but could not get it to work beyond this. How can I make it look like

USER ID |  USER_LON | USER_LAT
110, 64, -111

You need to parse the body to get the parse JSON with JSON.pare() method.

And then you can pass the values to the Parameterized query . using $1, $2, $3 place holders.

Example:

function addRecordUser(request, response) {
    console.log('into final add record user method');
    console.log(request);
    const rec = JSON.parse(request.body);
    let query = 'INSERT INTO user_table VALUES ($1, $2, $3)';
    let values = [rec.user_id, rec.user_lon, rec.user_lat];
    pool.query(query, values, (error, results) => {
        if (error) {
            throw error
        }
        console.log(results);
        response.status(201).send('Row added')
    })
}

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