Thursday, 25 May 2017

How to correctly set the request header?

When I create a poll, I currently get a 400 error which means the request is not properly formatted. I am trying to pass the authentication token through the request header.

What have I done wrong ?

service:

addPoll(poll: Poll) {
            const body = JSON.stringify(poll);
            const token = localStorage.getItem('token')
                ? '?token=' + localStorage.getItem('token')
                : '';
            const headers = new Headers({
              'Content-Type': 'application/json',
              'Authorization': token
            });
            return this.http.post('https://voting-app-10.herokuapp.com/poll', body, {headers: headers})
                .map((response: Response) => {
                    const result = response.json();
                    const poll = new Poll(
                        result.obj.title,
                        result.obj.choice1,
                        result.obj.choice2,
                        0,
                        0,
                        result.obj.user.firstName,
                        result.obj._id,
                        result.obj.user._id,
                        );
                    this.polls.unshift(poll);
                    return poll;
                })
                .catch((error: Response) => {
                    this.errorService.handleError(error.json());
                    return Observable.throw(error);
                });
        }

route:

router.post('/', function (req, res, next) {
    var decoded = jwt.decode(getToken(req.headers.authorization));
    //ETC...



via Coder1000

No comments:

Post a Comment