使用Polymer iron-ajax和Node.js发出CORS请求 [英] Make CORS Request with Polymer iron-ajax and Node.js
问题描述
我正在尝试使用Polymer和Node检索数据,但是正在努力获取有效的响应.我收到起飞前响应错误,提示不允许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
.
如何配置节点或客户端以加载响应?
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>
节点
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& pass = password :
请求的资源上不存在"Access-Control-Allow-Origin"标头.
因此,不允许访问来源' http://localhost:4001 . 响应的HTTP状态代码为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预检 ,请考虑安装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
这将处理飞行前响应和其他CORS方面,而无需在应用程序代码中从头开始手动编写自己的处理方式.
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.
这篇关于使用Polymer iron-ajax和Node.js发出CORS请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!