Angular2 application call node.js function

99封情书 提交于 2019-12-19 10:27:19

问题


Ok so I have an Angular2 application running on http://localhost:4200/, Inside this app I'm trying to call a function located in a seperate node.js application currently running on http://localhost:3000/

My call from the Angular2 application:

deletePhoto(photoId: string) {

    var options = new RequestOptions({
        headers: new Headers({
            'Accept': 'application/json',
            'Access-Control-Allow-Origin': 'http://localhost:4200'
        })
    });

    let url = `http://localhost:3000/delete?photoId=${photoId}`;

    this.http.post(url, options).subscribe(response => {
        let user = response.json()
        console.log(user);
    },
        err => {
            console.log('Unable to call delete photo', err);
        });

}

And this is my node.js function :

var express = require('express')

var app = express();

app.post('/delete', function (req, res) {

    req.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'POST');
    res.setHeader('Access-Control-Allow-Headers', '*');

    var photoId = req.query['photoId'];
    //var userId = req.query['userId'];
    res.json({ "photoId": photoId, "test": "Testing node server" })
})

However the error I receive in the browser is:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Now after googling this error, I read I needed to set the header on the requested resource so I added the req.setHeader on my node method but still with no avail, I did also set it within my Angular2 app to see if that's what it meant but sadly same result.

I have read up on cors but unfortunately I'm still confused by it.


回答1:


You must also add code to handle the OPTIONS request that browsers send for CORS preflights:

app.options('/delete', function(req, res) {
    res.send(200);
});

That addition just causes your Node app send a 200 response with no body with all the necessary Access-Control-* response headers.



来源:https://stackoverflow.com/questions/42323139/angular2-application-call-node-js-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!