当我以前将它作为一个应用程序运行时,我正在使用fetch从我的react组件调用Web API,没有问题,但是当我运行该应用程序与API分开运行时,出现了CORS错误,我的提取呼叫如下所示,
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呼叫也如下。
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代码:
[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:44368/api/communities”到“ http://localhost:3000”的访存已被CORS策略阻止:否“ Access-Control-Allow- “ Origin”标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。”
答案 0 :(得分:3)
您需要修改服务器。您需要
答案 1 :(得分:1)
在获取方法中添加mode: 'no-cors'
应该可以解决问题
fetch(clientConfiguration['communitiesApi.local'], {
mode: 'no-cors'
})
.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时,我喜欢使用chrome网站商店中的Allow CORS: Access-Control-Allow-Origin,在本地主机上开发Web应用程序时非常方便
答案 2 :(得分:1)
需要在服务端添加cors 这可以通过停止服务器然后
轻松完成npm install cors
然后将其添加到您的主路由器文件中,如果您使用多个文件进行路由
const express = require("express");
const router = express.Router();
const cors = require("cors");
router.use(cors());
你已经设置好了多文件路由器。
对于单文件路由器,您应该使用以下代码:
const express = require("express")
const app = express()
const cors = require("cors")
app.use(cors())
你已经设置好了 这应该可以解决错误
答案 3 :(得分:0)
感谢您可以通过在Web API上实现CORS来解决此问题,这是我所做的代码,但是在已经实现了Web Api并且我们需要使用Api的情况下,您的代码也能很好地工作不是去修改api的方法,那么您在客户端可以使用。这是我对Web API的更改
public void ConfigureServices(IServiceCollection services)
{
string configValue = Configuration.GetValue<string>("CORSComplianceDomains");
string[] CORSComplianceDomains = configValue.Split("|,|");
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://localhost:3000");
});
options.AddPolicy("AnotherPolicy",
builder =>
{
builder.WithOrigins(CORSComplianceDomains)
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
并在appsettings.json文件中添加了网址,以便任何用户都可以轻松地添加新的网址。
"CORSComplianceDomains": "http://localhost:3000|,|http://www.contoso.com"
非常感谢-我把我的答案放在这里,以便有人可以得到-感谢您的参与和帮助-非常感谢-非常感谢。