It can do a GET OK, but it just can't do a POST. I have tried all manner of Header combinations. Its to the localhost.
Here is my Reactjs App call
export function saveStaff(data) {
return fetch(baseUrl, {
mode: "no-cors",
method: "POST",
headers: {
Host: "localhost:44370",
Allow: "GET, POST",
Accept: "application/json, text/plain",
"Content-Type": "application/json"
},
body: { Name: "tuesday", Department: "tuesday", visitorcount: 0 } // data // JSON.stringify(data)
})
.then(handleResponse)
.catch(handleError);
}
Here are the headers from Postman this works!
POST /api/StaffNamesAPI HTTP/1.1
Host: localhost:44370
Allow: GET, POST
Content-Type: application/json
Accept: application/json, text/plain
User-Agent: PostmanRuntime/7.16.3
Cache-Control: no-cache
Postman-Token: a5b282c7-24e7-46a6-ba22-4f74a31fa9bd,2232ec6c-b3e9-4e29-88e3-abf63675486c
Host: localhost:44370
Accept-Encoding: gzip, deflate
Content-Length: 122
Connection: keep-alive
cache-control: no-cache
{"Name": "Wednesday TestWithPostman",
"Department": "Groan",
"visitorcount": 0 }
Here is the API Controller
[HttpPost]
[Consumes("application/json")] //https://github.com/aspnet/AspNetCore/issues/4396
public async Task<ActionResult<StaffNames>> PostStaffNames(StaffNames staffNames)
{
_context.StaffNames.Add(staffNames);
await _context.SaveChangesAsync();
return CreatedAtAction("GetStaffNames", new { id = staffNames.Id }, staffNames);
}
My class is simple at this stage
public class StaffNames
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public int VisitorCount { get; set; }
}
And in my startup.cs I have the CORS set up
//https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#ecors
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:3000/",
"http://www.contoso.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Here is my useCors
app.UseCors(MyAllowSpecificOrigins);
//https://stackoverflow.com/questions/52896068/reactasp-net-core-no-access-control-allow-origin-header-is-present-on-the-r
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
Thanks for your help, I have been pondering this for hours!