I have an axios post request on my Vue frontend which sends some data to an API endpoint (express). The problem is that I can't see any data on the controller that receive the post request.
//app.js
var express = require('express')
var cors = require('cors')
var app = express()
var port = process.env.port || 1337
app.use(cors({origin: true}));
var imagenmatriculaController = require('./controllers/imagenmatriculaController.js')()
app.use("/api/imagenmatricula", imagenmatriculaController)
app.listen(port, function () {})
//imagenmatriculaController.js
var express = require('express')
var router = express.Router()
var routes = function (){
router.route('/')
.post(function(req,res){
console.log(req.data)
res.json('ok')
})
return router
}
module.exports = routes
I do receive the request log on the server and the 'ok' back to the client but I get an undefined on the console.log(req.data);
//vue post
var headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*'
};
axios.post('http://localhost:1337/api/imagenmatricula', {
headers: headers,
data: 'test'
})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
console.log('ERROR::', error.response.data);
});
In order to receive json data on backend you need to setup parser. You could use body-parser. Then your code should look like this
var express = require('express')
var cors = require('cors')
var app = express()
var port = process.env.port || 1337
var bodyParser = require('body-parser')
app.use(cors({origin: true}));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
var imagenmatriculaController = require('./controllers/imagenmatriculaController.js')()
app.use("/api/imagenmatricula", imagenmatriculaController)
app.listen(port, function () {})
//imagenmatriculaController.js
var express = require('express')
var router = express.Router()
var routes = function (){
router.route('/')
.post(function(req,res){
console.log(req.body)
res.json('ok')
})
return router
}
module.exports = routes
Client should look like this:
var headers = {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*'
};
axios.post('http://localhost:1337/api/imagenmatricula', {
headers: headers,
data: { test: 'test' }
})
.then(response => {
console.log(response);
}).catch(error => {
console.log(error);
console.log('ERROR::', error.response.body);
});
If your routing on server is correctly setup, this should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With