我已经使用Node/Express创建了一个小API,并试图使用Angularjs拉数据,但由于我的html页面在localhost:8888和节点API在端口3000上监听下运行,我得到了No 'Access-Control-Allow-Origin'。我尝试使用node-http-proxy和Vhosts Apache,但没有太多成功,请参阅下面的完整错误和代码。

XMLHttpRequest无法加载localhost:3000。被请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问Origin 'localhost:8888'。”

// Api Using Node/Express    
var express = require('express');
var app = express();
var contractors = [
    {   
     "id": "1", 
        "name": "Joe Blogg",
        "Weeks": 3,
        "Photo": "1.png"
    }
];

app.use(express.bodyParser());

app.get('/', function(req, res) {
  res.json(contractors);
});
app.listen(process.env.PORT || 3000);
console.log('Server is running on Port 3000')

角码

angular.module('contractorsApp', [])
.controller('ContractorsCtrl', function($scope, $http,$routeParams) {

   $http.get('localhost:3000').then(function(response) {
       var data = response.data;
       $scope.contractors = data;
   })

HTML

<body ng-app="contractorsApp">
    <div ng-controller="ContractorsCtrl"> 
        <ul>
            <li ng-repeat="person in contractors">{{person.name}}</li>
        </ul>
    </div>
</body>

当前回答

在你的项目中安装cors依赖:

npm i --save cors

添加到您的服务器配置文件如下:

var cors = require('cors');
app.use(cors());

它适用于2.8.4 cors版本。

其他回答

这对我很管用。

app.get('/', function (req, res) {

    res.header("Access-Control-Allow-Origin", "*");
    res.send('hello world')
})

你可以根据自己的需要改变*。希望这能有所帮助。

应答码只允许localhost:8888。此代码不能部署到生产环境中,也不能部署到不同的服务器和端口名称中。

要让它适用于所有源,请使用下面的代码:

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

/** * Allow cross origin to access our /public directory from any site. * Make sure this header option is defined before defining of static path to /public directory */ expressApp.use('/public',function(req, res, next) { res.setHeader("Access-Control-Allow-Origin", "*"); // Request headers you wish to allow res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // Set to true if you need the website to include cookies in the requests sent res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); /** * Server is about set up. Now track for css/js/images request from the * browser directly. Send static resources from "./public" directory. */ expressApp.use('/public', express.static(path.join(__dirname, 'public'))); If you want to set Access-Control-Allow-Origin to a specific static directory you can set the following.

接受的答案是好的,如果你喜欢更短的东西,你可以使用一个插件称为cors可用的Express.js。

对于这种特殊的情况,使用起来很简单:

var cors = require('cors');

// use it before all route definitions
app.use(cors({origin: 'http://localhost:8888'}));

(您可能需要使用127.0.0.1而不是localhost。)

请求源需要与允许的源相匹配,你也可以有多个:

app.use(
  cors({origin: ['http://localhost:8888', 'http://127.0.0.1:8888']})
);

其他的答案对我都不管用。(包括cors包,或通过中间件设置报头)

套接字。IO 3^这工作不需要任何额外的包。

const express = require('express');
const app = express();

const server = require('http').createServer(app);
const io = require('socket.io')(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});