Axios获取CORS策略:仅在发送文件时,所请求的资源上没有'Access-Control-Allow-Origin'标头

 收藏

错误信息

Access to XMLHttpRequest at 'https://api.example.xyz/api/post' from origin 'https://app.example.xyz' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

仅当发送的表单中包含文件时才会发生这种情况

我已经在后端使用了cors

app.options("*", cors());
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "*");
  res.header("Access-Control-Allow-Headers", "*");
  next();
});

然后像这样设置axios

axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.headers.common["Access-Control-Allow-Origin"] = "*";

这就是使用redux dispatch分配表单的方式


  async function submit(e) {
    e.preventDefault();
    var form = new FormData(e.target); 
    await props
      .dispatch(insert(form)) <--the insert function
      .then(data => setNotification({ type: "success", ...data }))
      .catch(error =>
        setNotification({ type: "error", ...error.response.data })
      );
  }

插入功能

export function insert(data) {
  return dispatch => {
    return new Promise((resolve, reject) => {
      HTTP.post("/page", data)
        .then(data => {
          return resolve(data.data);
        })
        .catch(data => {
          return reject(data);
        });
    });
  };
}
回复