javascript - 在 Node.js/Express 和 AngularJS 中发出 CORS 请求

标签 javascript angularjs node.js express cors

我在堆栈溢出中看到了很多答案,其中说设置响应 header 将使您发出“CORS”请求。但是没有解决方案对我有用。我编写了以下代码:

//Server.js Code
var express = require('express'),
app = express();
app.all('*',function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With,   Content-Type, Accept");
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();

我尝试在客户端使用 $http 访问 URL 的内容:

//Controller.js
$http.get('http://domainA.com/a/ipadapi.php?id=135&client=ipad').success(function(response){
        alert("I got response");
    });

它在控制台中显示以下错误。

XMLHttpRequest cannot load http://domainA.com/a/ipadapi.php?id=135&client=ipad The 'Access-Control-Allow-Origin' header has a value 'http://example.xxxxx.com' that is not equal to the supplied origin. Origin 'http://localhost:3000' is therefore not allowed access.

注意:我是 NodeJS、Express 和 AngularJs 的新手

最佳答案

当您使用 CORS 传递凭据时,您需要锁定接受的来源。尝试将您的来源从 * 更改为“localhost:3000”

参见cross origin resource sharing with credentials

关于javascript - 在 Node.js/Express 和 AngularJS 中发出 CORS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30581954/

相关文章:

javascript - Angular : circular dependency of specific case

angularjs - 如何编译 $http 请求返回的数据?

node.js - Loopback - 隐藏请求访问 token

javascript - 如何更改 Angular Material 元素/组件的属性?

javascript - Bootbox 模式中的链接不可点击

javascript - 具有共享原型(prototype)的instanceof

javascript - 为什么它总是在 AngularJS 中选择第一个 TD 单元格

node.js - 未处理的PromiseRejectionWarning : TypeError: Cannot read property 'create' of undefined using Sequelize ORM

javascript - Express框架中的node-twitter

javascript - React 子组件可以更改存储在其父组件中的数据吗?