Axios Post request returns 204 No Content Status. What do I need to change to get a 201/persist the data?

試著忘記壹切 提交于 2021-02-10 18:04:51

问题


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 request:

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 controller action

        // 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 server logs

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 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();
            });
        }
    }

回答1:


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

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.

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. See if you can host UI as well from the same server as the backend.
  2. Enable CORS in the backend controller and set the right headers, at least for local executions (https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api)
  3. Enable a proxy in the UI hosting server to proxy requests (from the server side) to your backend. That way your axios request is sent to the same origin as the UI.


来源:https://stackoverflow.com/questions/63866468/axios-post-request-returns-204-no-content-status-what-do-i-need-to-change-to-ge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!