从angularjs连接到expressjs应用程序

时间:2015-10-10 16:47:09

标签: angularjs node.js express gruntjs cors

我正在尝试使用angularjs作为前端构建应用程序,并使用express js构建rest api。我使用yeoman构建了两个项目,我的angular应用程序在localhost:9000上运行,我的快速应用程序在localhost:3000上运行。当我尝试从角度表达js应用程序时,我收到跨域请求,有没有办法解决这个问题。

Express App中的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(冲突)

1 个答案:

答案 0 :(得分:0)

使用npm cors - https://github.com/expressjs/cors来允许cors请求。

var express = require('express')
  , cors = require('cors')
  , app = express();

app.use(cors());

app.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

app.listen(3000);