zoukankan      html  css  js  c++  java
  • axios -- has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

    项目中,如果遇到axios跨域请求,这种错误:

    Access to XMLHttpRequest at 'http://x.x.x:3000/api/add' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
    

     解决方案:

    跨域配置:

    //设置跨域请求
    app.all('*', function (req, res, next) {
      //设置请求头
      //允许所有来源访问
      res.header('Access-Control-Allow-Origin', '*')
      //用于判断request来自ajax还是传统请求
      res.header("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");
      //允许访问的方式
      res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
      //修改程序信息与版本
      res.header('X-Powered-By', ' 3.2.1')
      //内容类型:如果是post请求必须指定这个属性
      res.header('Content-Type', 'application/json;charset=utf-8')
      next()
    })
    

     当ContentType为application/json,会分两次发送请求。

    第一次,先发送method为options的请求到服务器,这个请求会询问服务器支持哪些请求方法(get,post等),支持哪些请求头等服务器的支持情况。

    等到这个请求返回后,如果我们准备发送的请求符合服务器规则,那么才会继续发送第二次请求,否则会在console中报错。

  • 相关阅读:
    20200807日报
    20200806日报
    《大道至简》读书感悟
    20200805日报
    20200804日报
    20200803日报
    20200802日报
    vue中mounted内如何调完异步方法再渲染
    小程序画布识别iPhone11
    np.meshgrid() 生成网格坐标函数
  • 原文地址:https://www.cnblogs.com/Super-scarlett/p/12545724.html
Copyright © 2011-2022 走看看