I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies.
In an attempt to resolve this, I set the headers in the middleware following suggestions from StackOverflow:
router.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
console.log('Something is happening.');
next(); // proceed to the next routes
});
However, this did not fix the problem. So, I looked into a CORS NPM package: https://www.npmjs.com/package/cors
I followed the installation guide and added it to my solution:
....
var cors = require('cors');
....
app.use(cors());
app.options('*', cors())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
But still no luck.
I am running out of ideas and unsure about what could be causing the issue.
Here is the client-side code snippet:
login() {
if(this.input.username != '' && this.input.password != '') {
//Execute Axios here
axios.post('http://localhost:8080/api/user/login',{
username:this.input.username,
password:this.input.password
})
.then(function (response) {
// handle success
console.log(JSON.stringify(response.data));
console.log(response.status);
console.log(response.headers);
//Router.push('Dashboard')
})
.catch(function (error) {
// handle error
console.log(JSON.stringify(error.data));
console.log(error.status);
console.log(error.headers);
})
.then(function () {
// always executed
});
} else {
console.log('A username and password must be present')
}
}
The post method itself:
router.route('/user/login/')
.post(function(req, res) {
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
User.findOne({ username: user.username}, function(err, dbuser) {
if (err)
res.send(err);
console.log('Error');
bcrypt.compare(user.password, dbuser.password, function(err, compareResult) {
console.log('Match!')
var token = jwt.sign({ username: user.username }, secret, {
expiresIn: 86400
});
res.cookie("test", user.username);
res.status(200).send({ auth: true, token: token });
console.log(token);
});
});
});