reactJS 中没有“Access-Control-Allow-Origin" [英] No 'Access-Control-Allow-Origin in reactJS

查看:22
本文介绍了reactJS 中没有“Access-Control-Allow-Origin"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 reactJS 或 react-native 环境的 axios post 方法中设置 Access-Control-Allow-Origin?我使用 CORS 附加组件,它可以工作,但我也想在标题中设置它,我尝试了这些方法,但没有一个不起作用.

I want to know how set Access-Control-Allow-Origin in axios post method at reactJS or react-native environment? I use CORS Add-ons and it works but I want to set it in the header too, I try these ways but none of them does not work.

axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';

let axiosConfig = {
  headers: {
    'method':'POST',
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Access-Control-Allow-Origin': '*',
  }
};

推荐答案

您需要在您的服务器端启用跨域请求.使用 Express 进行操作的片段如下

You need to enable cross origin request at your server end. A snippet of how you can do it using Express would be as follows

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

这将使所有请求都支持 CORS.根据您的要求进行调整.

This would enable all requests to support CORS. Adapt it as per your requirements.

检查 链接以获取更多信息.

Check this link for more information if you can not change the server.

这篇关于reactJS 中没有“Access-Control-Allow-Origin"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆