All my methods like SELECT, etc are OK, I can retrieve my data in Postman.
But, my method INSERT INTO to add data in my database does not work in Postman. The body seems to be not correct.
This is the body I tried to send with Postman :
{
"id": 2000,
"code": 4,
"alpha2": "AF",
"alpha3": "AFG",
"name_en": "Afghanistan",
"name_fr": "Afghanistan"
}
Here is the code in node.js :
app.post('/country', function (req, res) {
let country = req.body.country;
if (!country) {
return res.status(400).send({ error:true, message: 'Please provide country' });
}
mc.query("INSERT INTO country SET ? ", { country: country }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New country has been created successfully.' });
});
});
Here is the response I got in Postman :
{
"error": true,
"message": "Please provide country"
}
Here is my SQL Database :
Assuming you are using body-parser package and have correctly loaded it,
const bodyParser = require("body-parser);
app.use(bodyParser.json())
then, your payload is not correct.
You need to have the country
key in the root of the object -
{
"country": {
"id": 2000,
"code": 4,
"alpha2": "AF",
"alpha3": "AFG",
"name_en": "Afghanistan",
"name_fr": "Afghanistan"
}
}
Your current code is looking for req.body.country
when it does not exist. If you'll execute req.body.alpha3
you'll see what I mean.
-- Edit:
Your SQL also has issues.
--
Edit 2:
Based on the mysql package documentations, you should construct the query as follows -
mc.query("INSERT INTO country SET ? ", country, function (error, results, fields) {....
Don't wrap country inside another object assuming you create the object as I described before with country present in the root. Otherwise, just pass the req.body as it is (of course, you should be escaping the queries).