【发布时间】:2016-01-08 11:23:00
【问题描述】:
我正在尝试构建一个使用 angularjs 作为前端并使用 express js 休息 api 的应用程序。我使用 yeoman 构建了这两个项目,我的 angular 应用程序在 localhost:9000 上运行,我的 express 应用程序在 localhost:3000 上运行。当我尝试从 Angular 与 Express js 应用程序交谈时,我收到了一个跨域请求,有什么办法可以解决这个问题。
Express 应用中的 app.js
var routes = require('./routes/signup')(app); //This is the extra line
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "{GRUNT_SERVER}");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
app.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
angularjs 应用中的 app.js
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.withCredentials = true;
错误
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:9000' is therefore not allowed access.
The response had HTTP status code 409.
编辑
这是我添加到 app.js 文件中的代码:
// allow CORS:
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
next();
});
这也会引发与以前相同的错误(“请求的资源上不存在‘Access-Control-Allow-Origin’标头。”)。
编辑
使用后
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
这是抛出 POST localhost:3000/signup 409(冲突)
【问题讨论】:
-
几乎有 100 个问题问的问题基本相同:stackoverflow.com/…。这些都没有帮助吗?
标签: node.js angularjs express gruntjs http-status-code-409