Reputation: 404
I am currently trying to do a simple post method to my API through the browser and it fails. When I do the same on postman, the POST method goes without problem. It returns a json string and returns 2 cookies.
I have tried to set the headers in the middleware like I found on SO:
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(); // make sure we go to the next routes and don't stop here
});
Unfortunately this did not solve the issue, so I went out for more research and found a NPM package about Cors: https://www.npmjs.com/package/cors
so I went through 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());
Also, without luck.
I am pretty much out of ideas, and have no clue what could be the issue here.
Here is the client side:
login() {
if(this.input.username != '' && this.input.password != '') {
//We should execute our 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')
}
}
but that seems to be OK to me.
Post method itself:
router.route('/user/login/')
.post(function(req, res) {
var user = new User(); // create a new instance of the user model
user.username = req.body.username; // set the users name (comes from the request)
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!')
// create a token
var token = jwt.sign({ username: user.username }, secret, {
expiresIn: 86400 // expires in 24 hours
});
res.cookie("test", user.username);
res.status(200).send({ auth: true, token: token });
console.log(token);
});
});
});
Upvotes: 3
Views: 7532
Reputation: 1786
When using the cors
module here are the settings I use to allow everything cors related
const corsOptions = {
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
credentials: true,
preflightContinue: true,
maxAge: 600,
};
app.options('*', cors(corsOptions));
app.use(cors(corsOptions));
Upvotes: 3