2015-10-10 55 views
0

我想用angularjs作爲前端構建一個應用程序,並使用express js來休息api。我使用yeoman構建了兩個項目,我的angular應用程序在localhost:9000上運行,而我的快速應用程序在localhost:3000上運行。當我嘗試從角度表達js應用程序時,我得到了一個跨域請求,有沒有什麼方法可以解決這個問題。連接到angularjs的expressjs應用程序

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!' }); 
}); 

app.js在angularjs應用

$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(); 
}); 

這也拋出了同樣的錯誤(「否‘訪問控制允許來源’標頭出現在請求的資源「)。

編輯

使用後

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

app.use(cors()); 

這是扔POST本地主機:3000 /註冊409(衝突)

+0

幾乎有100個問題基本上提出了同樣的問題:http://stackoverflow.com/search?q=angular+express+Access-Control-Allow-Origin。這些都沒有幫助嗎? – Claies

+0

[如何在Express/Node.js中允許CORS?](http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-node-js) – Claies

回答

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); 
+0

當我嘗試向用戶提到的代碼,我收到以下錯誤。 POST http:// localhost:3000/signup 409(Conflict) – Anuteja

+0

您能展示更多代碼嗎?因爲上面的代碼工作正常,我認爲你有其他代碼的問題。 –