Angular2应用程序调用node.js函数 [英] Angular2 application call node.js function

查看:108
本文介绍了Angular2应用程序调用node.js函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我有一个在http://localhost:4200/上运行的Angular2应用程序,在此应用程序内,我试图调用一个位于当前在http://localhost:3000/上运行的单独node.js应用程序中的函数

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/

我从Angular2应用程序拨打的电话:

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);
        });

}

这是我的node.js函数:

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:

对预检请求的响应未通过访问控制检查:所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问' http://localhost:4200 '.

现在,在搜索了此错误之后,我读到我需要在请求的资源上设置标头,因此我在node方法上添加了req.setHeader,但仍然无济于事,我也确实在Angular2中进行了设置应用程序以查看其含义,但可悲的是结果相同.

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.

我已经阅读过cors,但不幸的是,我仍然对此感到困惑.

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

推荐答案

您还必须添加代码来处理浏览器为

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);
});

这种添加只会导致您的Node应用发送带有所有必需的Access-Control-*响应标头的无正文的200响应.

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

这篇关于Angular2应用程序调用node.js函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆