Axios Post请求返回204无内容状态.我需要更改什么才能获得201/持久化数据



当本地尝试在我的NodeJS前端应用程序上使用Axios向我的.NET核心本地服务器发出POST请求时,服务器返回204,Axios请求返回挂起的承诺。我需要更改什么才能获得201创建状态/保持记录?当我在Postman中尝试发布请求时,它运行得很好,但我的应用程序表现不同。

axios请求:

export const postStudent = (firstName: string, lastName: string, yearLevel: string) => {
return axios
.post(
`${externalAppURL}/Students/`,
{
id: Math.floor(Math.random() * 10000),
firstName: firstName,
lastName: lastName,
}
)
.then(function (response: any) {
console.log(response);
})
.catch(function (error: Error) {
console.log(error);
});
}

.NET控制器动作

// POST: api/Students
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<Student>> PostStudent(Student student)
{
_context.Students.Add(student);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetStudent), new { id = student.Id }, student);
}

.NET服务器日志

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 OPTIONS https://localhost:5001/api/api/Students/  
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
CORS policy execution successful.
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 2.6859ms 204 

Axios后返回值

Promise {[[PromiseState]]: 'pending', [[PromiseResult]]: undefined}
[[PromiseResult]]:undefined
[[PromiseState]]:'pending'
__proto__:Promise

启动.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(
options => options.WithOrigins("http://localhost:3000").AllowAnyMethod()
);
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

我注意到来自.NET服务器的控制台是对OPTIONS请求的响应,而不是POST请求。204与此相对应。

看起来您正试图从一个UI向localhost:5001发出请求,该UI是从运行在不同源(如localhost:8080(上的服务器呈现的。这将导致飞行前请求(使用HTTP方法OPTIONS(,该请求确定您的服务器是否应为此服务。出于安全原因,CORS拒绝错误对您的javascript不可见。您可以在此处找到更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.

话虽如此,如果此请求是通过浏览器发出的,请检查浏览器控制台日志——它们通常会打印CORS错误。

如果你想克服这个问题,你有两个选择:

  1. 查看是否也可以从与后端相同的服务器托管UI
  2. 在后端控制器中启用CORS并设置正确的标头,至少对于本地执行(https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api)
  3. 在UI托管服务器中启用代理,将请求(从服务器端(代理到后端。这样,您的axios请求就会发送到与UI相同的原点

最新更新