問題描述
我正在嘗試使用 Polymer 和 Node 檢索數(shù)據(jù),但正在努力獲得有效的響應(yīng).我收到一個飛行前響應(yīng)錯誤,提示 access-control-allow-origin
是不允許的.
I am trying to retrieve data using Polymer and Node, but am struggling to get a valid response back. I get a pre-flight response error that says the access-control-allow-origin
is not allowed.
我在 localhost:4001
上運行 Polymer,在 localhost:8080
上運行 Node.
I am running Polymer on localhost:4001
and Node on localhost:8080
.
如何配置節(jié)點或客戶端以加載響應(yīng)?
How can I configure either Node or the Client to load a response?
客戶
<iron-ajax id="ajaxUser"
url="http://localhost:8080/node/api/mssql/login"
method="post"
handle-as="json"
Content-Type="application/json"
headers='{"Access-Control-Allow-Origin": "*"}'
params="[[params]]"
on-response="saveUserCredentials"
last-response="{{user}}"></iron-ajax>
節(jié)點
const corsOptions = {
allowedHeaders: ['Content-Type', 'Access-Control-Allow-Origin']
}
app.options('*', cors(corsOptions))
...
app.use((req, res, next) => { // Enable Cross-Origin Resource Sharing (CORS)
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, x-api-key")
next()
})
錯誤
加載失敗
http://localhost:8080/login?username=user&password=password:
請求的資源上不存在Access-Control-Allow-Origin"標頭.
因此,Origin 'http://localhost:4001' 是不允許訪問的.響應(yīng)的 HTTP 狀態(tài)代碼為 400.
Failed to load
http://localhost:8080/login?username=user&password=password:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4001' is therefore not allowed access. The response had HTTP status code 400.
推薦答案
問題代碼段中的Node配置沒有處理OPTIONS
請求.
The Node configuration in the code snippet in the question doesn’t handle OPTIONS
requests.
為了確保正確處理 CORS 預(yù)檢,考慮安裝 npm cors
包:
To ensure CORS preflights get handled correctly, consider installing the npm cors
package:
npm install cors
然后做這樣的事情:
var express = require('express')
, cors = require('cors')
, app = express();
app.options('*', cors()); // preflight OPTIONS; put before other routes
這將處理預(yù)檢響應(yīng)和其他 CORS 方面,而無需您在應(yīng)用程序代碼中從頭開始手動編寫自己的處理.
That’ll handle the preflight response and other CORS aspects without you needing to manually write your own handling from scratch in your application code.
https://www.npmjs.com/package/cors#configuration-option 提供了所有選項的更多詳細信息.
https://www.npmjs.com/package/cors#configuration-option has more details on all the options.
這篇關(guān)于使用 Polymer Iron-ajax 和 Node.js 發(fā)出 CORS 請求的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!