Axios Post 请求返回 204 No Content Status.我需要更改什么才能获得 201/保留数据? [英] Axios Post request returns 204 No Content Status. What do I need to change to get a 201/persist the data?

查看:92
本文介绍了Axios Post 请求返回 204 No Content Status.我需要更改什么才能获得 201/保留数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在本地尝试使用 NodeJS 前端应用程序上的 Axios 向我的 .NET Core 本地服务器发出 POST 请求时,服务器返回 204,而 axios 请求返回未决承诺.我需要更改什么才能实现 201 创建状态/保留记录?当我在 Postman 中尝试发布请求时,它运行良好,但我的应用程序的行为有所不同.

When locally attempting to make a POST request with Axios on my NodeJS front-end app to my .NET core local server, the server returns a 204 and the axios request returns a pending promise. What do I need to change to achieve a 201 created status/persist the record? When I try a post request in Postman it works perfectly, but my app however, behaves differently.

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 post返回值

Axios post return value

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

Startup.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 对应于此.

I notice your console from .NET server is the response for an OPTIONS request and not your POST request. And 204 corresponds to that.

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

Looks like you are trying to make a request to localhost:5001 from a UI rendered from a server running on a different origin (such as localhost:8080). This would cause a pre-flight request (with HTTP method OPTIONS) that determines whether your server should serve this or not. For security reasons, CORS rejection errors will not be visible to your javascript. You can find more information here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.

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

Having said that if this request is through a browser, please check browser console logs - they usually print CORS errors.

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

If you want to overcome this, you have couple of options:

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

这篇关于Axios Post 请求返回 204 No Content Status.我需要更改什么才能获得 201/保留数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆