问题
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:
- See if you can host UI as well from the same server as the backend.
- 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)
- 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