请求的资源上不存在“Access-Control-Allow-Origin”标头。

时间:2016-12-08 02:24:23

标签: angularjs cors

我已经看到了几个问题和答案,我的工作已经完成了一半。

我有一个带有url api.domain.com的node.js api服务器和一个位于www.domain.com的nginx服务器上的网站,当我在api服务器上执行以下请求时,我看到了请求我看到它被解析并放入数据库。但是,在客户端我没有立即返回,最后我会看到No 'Access-Control-Allow-Origin' header is present on the requested resource.

我知道导致此行为的原因是什么,但它不应该在它到达API服务器之前抛出错误?另请注意,node.js服务器已启用cors。应该回来的回应是json。

$http({
            method: 'POST',
            url: "http://api.domain.com/addtrans/" + $scope.accountID,
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            transformRequest: function (obj) {
                var str = [];
                for (var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            },
            data: {
                payload: JSON.stringify(trans)
            }
        }).success(function (result) {
            $scope.trans = {};
            console.log(result);
        });

3 个答案:

答案 0 :(得分:0)

我在所有项目中都使用了以下中间件,并且它已被证明效果最佳。

const allowCors = (req, res, next) => {

    /** Allow all origins, for now TODO */
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Headers', 'Authorization, Content-Type');
    res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');

    /** Browser check for pre-flight request to determine whether the server is webdav compatible */
    if ('OPTIONS' == req.method) {
        res.sendStatus(204);
    }
    else next();
};

// Put this code before the routes you want to allow CORS to
app.use(allowCors);

出于安全原因,您应该将Allow-Origin更改为更受限制的内容。

以上代码涵盖CORS以及大多数浏览器的预飞行(这是我们在开始时遇到的主要问题)。

答案 1 :(得分:0)

我刚才用过(表达3.x):

// npm install --save cors
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(express.static());
app.get('*', function(){});
require('http').createServer(app).listen(3000)

答案 2 :(得分:0)

请记住,cors标题应该是来自服务器的响应,而不是来自客户端的请求。

您可以使用中间件在服务器上启用cors:

Label4 = canvas.create_text(300, 460, text=itemThree, font=('Impact', -30), fill="yellow")
相关问题