zoukankan      html  css  js  c++  java
  • axios跨域请求报错:Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

    在做项目时,用到axios,数据用post提交时,老是报错,错误提示为:

    1 Access to XMLHttpRequest at 'http://127.0.0.1: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', 'X-Requested-With')
      //允许访问的方式
      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()
    })

    这是因为我在后端设置跨域请求的时候没有所需的请求类型。于是做了如下修改:

    //设置跨域请求
    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()
    })

    结果就可以啦。

  • 相关阅读:
    401. Binary Watch
    46. Permutations
    61. Rotate List
    142. Linked List Cycle II
    86. Partition List
    234. Palindrome Linked List
    19. Remove Nth Node From End of List
    141. Linked List Cycle
    524. Longest Word in Dictionary through Deleting
    android ListView详解
  • 原文地址:https://www.cnblogs.com/joyco773/p/11473963.html
Copyright © 2011-2022 走看看