React组件已被CORS策略阻止:请求的资源上不存在"Access-Control-Allow-Origin"标头 [英] React component has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

查看:382
本文介绍了React组件已被CORS策略阻止:请求的资源上不存在"Access-Control-Allow-Origin"标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我以前将其作为一个应用程序运行时,我使用fetch从我的react组件调用Web API,没有问题,但是当我运行该应用程序与API分开进行反应时,出现了CORS错误,我的提取呼叫如下所示,

I am calling the Web API from the my react component using fetch when I used to run it as one application, there was no problem, but when I am running the application react separate from API, I am getting the CORS error, my fetch call is as below,

    componentDidMount() {
    console.log(clientConfiguration)

    fetch(clientConfiguration['communitiesApi.local'])
        .then((response) => {
            return response.json();                
        })
        .then(data => {
            console.log(data);
            let communitiesFromApi = data.map(community => { return { value: community, display: community } });
            this.setState({ communities: [{ value: '', display: 'Select a Community...' }].concat(communitiesFromApi) });    

        }).catch(error => {
            console.log(error);
        });
};

和我使用Axios的POST呼叫,如下所示.

and my POST call using Axios as below also.

    handleDownload = (e) => {
    e.preventDefault();

    var formData = new FormData();
    formData.append('communityname', this.state.selectedCommunity);
    formData.append('files', JSON.stringify(this.state['checkedFiles']));

    let url = clientConfiguration['filesApi.local'];
    let tempFiles = clientConfiguration['tempFiles.local'];

    axios({
        method: 'post',
        responseType: 'application/zip',
        contentType: 'application/zip',
        url: url,
        data: formData
    })
        .then(res => {       
            var fileName = `${this.state['selectedCommunity']}.zip`;
            saveAs(`https://localhost:44352/TempFiles/${res.data}`, fileName);
        });
};

这是我的服务器端api代码:

Here is my server side api code:

        [HttpGet("{communityName}")]
    public string Get(string communityName)
    {
        string rootPath = Configuration.GetValue<string>("ROOT_PATH");
        string communityPath = rootPath + "\\" + communityName;

        string[] files = Directory.GetFiles(communityPath);

        List<string> strippedFiles = new List<string>();
        foreach (string file in files)
        {
            strippedFiles.Add(file.Replace(communityPath + "\\", ""));
        }

        return JsonConvert.SerializeObject(strippedFiles);
    }

    [HttpPost]
    public string Post([FromForm] string communityName, [FromForm] string files) //FileContentResult
    {
        var removedInvalidCharsFromFileName = removeInvalidCharsFromFileName(files);
        var tFiles = removedInvalidCharsFromFileName.Split(',');
        string rootPath = Configuration.GetValue<string>("ROOT_PATH");
        string communityPath = rootPath + "\\" + communityName;

        byte[] theZipFile = null;

        using (MemoryStream zipStream = new MemoryStream())
        {
            using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                foreach (string attachment in tFiles)
                {
                    var zipEntry = zip.CreateEntry(attachment);

                    using (FileStream fileStream = new FileStream(communityPath + "\\" + attachment, FileMode.Open))
                    using (Stream entryStream = zipEntry.Open())
                    {
                        fileStream.CopyTo(entryStream);
                    }
                }
            }

            theZipFile = zipStream.ToArray();
        }

        ////return File(theZipFile, "application/zip", communityName + ".zip");

        string tempFilesPath = Configuration.GetValue<string>("Temp_Files_Path");

        if (!System.IO.Directory.Exists(tempFilesPath))
            System.IO.Directory.CreateDirectory(tempFilesPath);

        System.IO.File.WriteAllBytes($"{tempFilesPath}\\{communityName}.zip", theZipFile);

        //return System.IO.File.ReadAllBytes($"{tempFilesPath}\\Test.zip");

        //return $"{tempFilesPath}\\{communityName}.zip";
        return $"{communityName}.zip";
    }

我得到了Get的错误,如下所示:访问在' https://localhost:来源' http://localhost:3000 '的原点44368/api/communities '已被CORS阻止策略:所请求的资源上没有"Access-Control-Allow-Origin"标头.如果不透明的响应满足您的需求,请将请求的模式设置为"no-cors",以在禁用CORS的情况下获取资源."

And I am getting the error for Get as below: "Access to fetch at 'https://localhost:44368/api/communities' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

推荐答案

您需要修改服务器.您需要

You'll need to modify your sever. You'll need to

  1. 在服务器端启用CORS,并且
  2. 将您将在其中托管前端的域添加到允许的来源"列表中.

这篇关于React组件已被CORS策略阻止:请求的资源上不存在"Access-Control-Allow-Origin"标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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