Вы можете получить доступ к телу запроса почтового запроса в объекте req
.
Чтобы проанализировать тело post
, вам нужно добавить пакет body-parser
для анализа тела запроса.
Сначала установите пакет body-parser
.
>$ npm i --save body-parser
Затем добавьте пакет в файл проекта.
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // To parse the Json data
А затем получите доступ к своему телу в объекте req
.
app.post('/post/vaccination/:petid/:speciesName/:vaccineType/:userName', function (req, res) {
const {pension} = req.body;
connection.query("INSERT INTO AnotherTable(col1) VALUES(?)", [pension], function (error, rows, fields) {
if (!error) {
console.log('Added');
}
else {
console.log('error 1' + JSON.stringify(error, undefined, 2));
}
});
});
Полный рабочий код:
var express = require('express');
var app = express();
var mysql = require('mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var connection = mysql.createConnection({
user: 'root',
host: 'localhost',
database: '',
password: ''
});
app.post('/post/vaccination/:petid/:speciesName/:vaccineType/:userName', function (req, res) {
//should it be request.body? const {pension} = request.body
connection.query("INSERT INTO AnotherTable(col1) VALUES(?)", [pension], function (error, rows, fields) {
if (!error) {
console.log('Added');
res.status(201).send("added");
}
else {
console.log('error 1' + JSON.stringify(error, undefined, 2));
res.status(500).send('error 1' + JSON.stringify(error, undefined, 2));
}
});
});
Обратите внимание, что необходимо отправить ответ как в случае ошибки, так и в случае успеха.