Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

express - Make CORS Request with Polymer iron-ajax and Node.js

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.

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?

Client

<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>

Node

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

Error

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Node configuration in the code snippet in the question doesn’t handle OPTIONS requests.

To ensure CORS preflights get handled correctly, consider installing the npm cors package:

npm install cors

And then do something like this:

var express = require('express')
  , cors = require('cors')
  , app = express();
app.options('*', cors()); // preflight OPTIONS; put before other routes

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 has more details on all the options.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...