I am working on the voting app and trying to get the front-end and back-end to communicate with each other.
I am building the front-end with Angular 2 with systemJS, which is using localhost:3000
My backend runs on localhost:9000
I added this middleware to my backend:
app.use(function (req, res, next) {
console.log('middleware working')
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept, x-auth");
next();
});
Once I did that, I could get the login and create user functions to work. (POST /api/login and POST /api/users)
Now I am trying to create a survey (POST /api/surveys) and it’s not working. The main difference is that creating a survey requires authentification, so the POST request is sending a header: x-auth:token
I added x-auth to the Access-Control-Allow-Headers in the middleware. Still not working.
Here’s the front-end code doing the post request:
saveSurvey(newSurvey: Survey, token):Observable<Survey>{
let headers = new Headers({'Content-Type':'application/json', 'x-auth':token});
let options = new RequestOptions({headers: headers});
return this.http.post(apiUrl+'/surveys',JSON.stringify(newSurvey), options)
.map((res:Response)=>res.json())
.catch((error:any)=>Observable.throw(error.error || 'Server error'))
}
I have included a console.log(token) and console.log(newSurvey) and both log the correct information.
and the backend code:
app.post('/api/surveys', authenticate, function(req,res){
console.log('app.post surveys'); // not logging anything. There is also a console.log in the authenticate middleware and it's not logging either.
var body = req.body;
body._creator = req.user._id;
var newSurvey = new Survey(body);
console.log(newSurvey)
newSurvey.save().then(function(survey){
res.send(survey);
}).catch(function(err){
res.status(400).send(err)
})
});
What am I missing??