我正在尝试使用axios将数据对象发送到后端。。。问题是我应该在后端也使用axios吗?我似乎无法获得价值。
axios({
method: 'post',
url: '/encrypt',
data: {
firstName: 'Fred',
lastName: 'Flintstone',
},
//headers: {'Authorization': 'Bearer ...'}
});
app.post('/encrypt', (request, response) => {
console.log(request.body, 'Request................');
});
请确保包含body解析器。
const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')
// create application/json parser
const jsonParser = bodyParser.json()
app.post('/encrypt', jsonParser, (req, res) => {
console.log(req.body);
res.send(req.body);
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
以及客户端
const axios = require('axios').default;
axios({
method: 'post',
url: 'http://localhost:3000/encrypt',
data: {
firstName: 'Fred',
lastName: 'Flintstone',
},
//headers: {'Authorization': 'Bearer ...'}
});
尝试修复代码并根据语法进行编写。Axios承诺。
axios.post('/encrypt', {
firstName: 'Fred',
lastName: 'Flintstone' }
).then(function (response) {
console.log(response)}).catch(function (error) {
console.log(error)
});