如何在尝试获取资源时解决"TypeError:NetworkError". [英] How to resolve "TypeError: NetworkError when attempting to fetch resource."
问题描述
当我使用aurelia-fetch-client将json数据发布到服务器时,出现此错误"TypeError:尝试获取资源时出现NetworkError".我认为您的回答对我非常有用.
When I use aurelia-fetch-client to post json data to server and I got this error "TypeError: NetworkError when attempting to fetch resource." I think your answer is very useful to me.
-
post.html
<template>
<section>
<form role="form" submit.trigger="signup()">
<div class="form-group">
<label for="OrganisationId">OrganisationId</label>
<input type="text" value.bind="organisationId" placeholder="OrganisationId">
</div>
<div >
<label for="OrganisationName">OrganisationName</label>
<input type="OrganisationName" value.bind="organisationName" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Enter</button>
</form>
</section>
</template>
post.js
import 'fetch';
import { HttpClient, json } from 'aurelia-fetch-client';
let httpClient = new HttpClient();
export class signup {
heading1 = "Welome to User";
organisationId = "";
organisationName = "";
signup() {
alert("calliong");
var myUser1 = { organisationId: this.organisationId, organisationName: this.organisationName }
console.log(myUser1);
httpClient.fetch('http://172.16.0.26:8085/employee-management/rest/employees/addOrganisations', {
method: "POST",
body: JSON.stringify(myUser1)
})
.then(response => response.json())
.then(data => {
console.log(data);
});
}
}
推荐答案
这可能与跨域资源共享(CORS)有关.
This is probably related to Cross-Origin Resource Sharing (CORS).
跨域资源共享(CORS)机制为Web服务器提供了跨域访问控制,该访问控制可实现安全的跨域数据传输.现代浏览器在API容器(例如XMLHttpRequest或Fetch)中使用CORS来减轻跨源HTTP请求的风险. (来源: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
如果您使用的是Chrome,则可以尝试通过命令chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
在Windows中使用运行",并查看是否可以在该环境中运行代码.这将允许访问任何"access-control-allow-origin"标头请求.
If you have Chrome you could try using Run in Windows with the command: chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
and see if you can run your code in that environment. This will allow access to no 'access-control-allow-origin' header requests.
我尝试在Chrome,Firefox和Edge中正常运行部分代码,并遇到相同的CORS错误.但是,当我使用上述命令时,它确实运行了.您没有提供太多信息来继续下去,但是您可能必须在服务器端以及代码中进行一些更改.
I tried running parts of your code normally in Chrome, Firefox and Edge and got the same CORS errors. It did however run when I used the above command. You didn't give too much information to go on, but you might have to do some changes server side as well as in your code.
上面的命令以及有关CORS的更多信息可以在SO上找到:在请求的资源上不存在"Access-Control-Allow-Origin"标头"
The command above and more good information about CORS can be found here on SO: "No 'Access-Control-Allow-Origin' header is present on the requested resource"
希望这至少可以为您指明正确的方向.
Hopefully this can at least point you in the right direction.
这篇关于如何在尝试获取资源时解决"TypeError:NetworkError".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!