Axios发布请求返回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?

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

问题描述

在本地尝试通过NodeJS前端应用程序上的Axios向我的.NET Core本地服务器发出POST请求时,服务器返回204,并且axios请求返回未完成的Promise.要达到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发布返回值

Axios post return value

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

Startup.cs

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并设置正确的标头( 查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆