typescript - Axios Post 请求返回 204 No Content Status。我需要更改什么才能获得 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 与此相对应。
看起来您正在尝试从运行在不同来源(例如 localhost:8080)上的服务器呈现的 UI 向 localhost:5001 发出请求。这将导致一个飞行前请求(使用 HTTP 方法 OPTIONS)来确定您的服务器是否应该提供此服务。出于安全原因,您的 JavaScript 不会看到 CORS 拒绝错误。您可以在此处找到更多信息:https ://developer.mozilla.org/en-US/docs/Web/HTTP/CORS 。
话虽如此,如果此请求是通过浏览器发出的,请检查浏览器控制台日志 - 它们通常会打印 CORS 错误。
如果你想克服这个问题,你有几个选择:
- 看看您是否也可以从与后端相同的服务器托管 UI。
- 在后端控制器中启用 CORS 并设置正确的标头,至少对于本地执行(https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-内网 api )
- 在 UI 托管服务器中启用代理以将请求(从服务器端)代理到您的后端。这样,您的 axios 请求将被发送到与 UI 相同的来源。
推荐阅读
- javascript - 如何在 ISODate 值中查询忽略其时间的日期
- c# - 如何使用`try`和`using`从方法中填写并返回`DataTable`?
- python - 命令 PhaseScriptExecution 失败,退出代码为非零,Xcode 10.1 dyld:未加载库:/usr/local/opt/readline/lib/libreadline.7.dylib
- c# - Mp4 流不适用于 c# webserver 中的所有文件
- apache-spark - 在 PySpark 中使用 kerberos 访问 Vertica
- php - 巴西收货地址正常化状态
- javascript - JS,Express:无论遵循以下指南,都无法在目录中查找视图
- angular - 理解角度分量的问题
- cypress - 检查页面上是否存在记录
- sql - 无法使用 spark SQL 创建表:创建 Hive TABLE (AS SELECT) 需要 Hive 支持;