Rocco M Rocco M - 1 month ago 8
MySQL Question

MYSQL + Node.JS Post Request Confusion

I am very new to networking and I have this code which, when I use a REST API like Postman, does exactly what I want it to do:

router.post('/', function(req,res,next){
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function(err, conn){
if(err)
{
console.error('SQL Connection error: ', err);
return next(err);
}
else
{
var query = conn.query("INSERT INTO coordinates (id,lat,lon) VALUES(3,2,1);");
if(err)
{
console.error('SQL error: ', err);
return next(err);
}
res.json("Coordinates sent.");
}
})
} );


That is, it sends the query request to the MYSQL database. My question is, how do I do this without using Postman to send the POST request?

Thank you.

Answer

You can't unless you make a post request from within your application or something. If you don't intend on sending data, you can just make it a GET request by changing

router.post('/', function(req,res,next){

to

router.get('/', function(req,res,next){

Then you can just go to the relevant URL from your browser. If you're using chrome and you just wanna see the JSON data, I'd also recommend installing the JSONView chrome extension.

EDIT

Here's the example request using request-promise

var request = require('request-promise');
var objectData = {
    name: 'Bruce',
    alias: 'Batman'
};
var options = {
    method: 'POST',
    uri: 'http://your.api/endpoint/',
    body: objectData,
    json: true // Automatically stringifies the body to JSON
};

request(options).then(function(response){
    // handle success response
}, function(error){
    // handle error response
})
Comments