无代理处理post非简单请求跨域问题

express下

在处理纯http服务post请求的时候的跨域问题

即使在服务端先加入

Access-Control-Allow-Origin: *(get即时有效)

会出现

  Failed to load http://127.0.0.1:3000/heros: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access.
 的报错

参考资料由于对于数据的操作属于非简单请求,当浏览器真正操作数据前需要做一次‘preflight’当预检成功会才会发送数据操作

预检请求的方式为option,所以可以在后台app.js中通过判断请求类型为option时进行预检的通过返回

const app = express()

// 处理预检,CORS 默认支持 get
// 其他需要单独处理
app.use((req, res, next) => {
  // 如果请求方法是 options ,则我认为是浏览器的非简单预检请求
  if (req.method.toLowerCase() === 'options') {
    // 处理预检请求的响应
    // return 的目的是不让代码继续往后执行了
    return res
      .status(200)
       .set('Access-Control-Allow-Origin', '*')
      // .set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
       .set('Access-Control-Allow-Headers', 'Content-Type')
       .end()
   }

  // 非预检请求直接跳过该中间件的处理
  next()
 })
 

资料:http://www.ruanyifeng.com/blog/2016/04/cors.html

猜你喜欢

转载自www.cnblogs.com/herewego/p/9283846.html