[英]Angular ERR_CONNECTION_REFUSED error during post request
I'm using CORS to connect Angular to the Database via .NET WebAPI but I'm getting this error:我正在使用 CORS 通过 .NET WebAPI 将 Angular 连接到数据库,但我收到此错误:
I can't pinpoint if the problem is on Angular or on the .NET side so any help is appreciated.我无法确定问题是在 Angular 还是在 .NET 方面,因此不胜感激。 Here are my angular component + service.
这是我的 angular 组件 + 服务。 Let me know if you need more info:
如果您需要更多信息,请告诉我:
export class SleepComponent implements OnInit {
constructor(public service : SleepService) { }
ngOnInit(): void {
this.resetForm();
}
resetForm(form?: NgForm) {
if(form!=null)
form.resetForm();
this.service.formData = {
SleepId : null,
Start: '',
Finish: '',
}
}
onSubmit(form : NgForm) {
this.insertRecord(form)
}
insertRecord(form: NgForm) {
console.log(this.service.formData.Finish)
this.service.postSleep(form.value).subscribe(
res=> { this.resetForm(form) }
),
err => {
console.log(err);
}
}
export class SleepService {
formData: Sleep;
readonly rootUrl = "https://localhost:44398/api"
constructor(private http: HttpClient) { }
postSleep (formData: Sleep) {
return this.http.post(this.rootUrl+'/main_tb', formData )
}
here's the api controller:这是 api controller:
[ResponseType(typeof(main_tb))]
public IHttpActionResult Postmain_tb(main_tb main_tb)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.main_tb.Add(main_tb);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = main_tb.SleepId }, main_tb);
}
Here's the webconfig.cs这是 webconfig.cs
{
//Enable CORS
config.EnableCors(new EnableCorsAttribute("http://localhost:4200/", headers:"*", methods: "*"));
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Please add below configuration to your web config请将以下配置添加到您的 web 配置中
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="accept,accesstoken,authorization,cache-
control,pragma,content-type,origin" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS,TOKEN" />
</customHeaders>
</httpProtocol>
and Here is webapi cors config这是 webapi cors 配置
var cors = new EnableCorsAttribute("http://localhost, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS,TOKEN");
config.EnableCors(cors);
If its working fine from Postman not from a browser its a CORS issue, You can check in the inspect network Tab for preflight request (OPTIONS) kindly confirm its working如果它从 Postman 工作正常而不是从浏览器它是 CORS 问题,您可以在检查网络选项卡中检查预检请求(选项)请确认其工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.