Fetch Post issues with CORS not getting header
As suggested by someone in another post, do the equivalent of this to your server-side assuming you are not using Nodejs. Note, my client-side where I was having a similar issue is Reactjs powered, that makes us even
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
I have since switched to this solution for my dotnet core webAPi. I find it's cleaner since I don't need a webconfig plus the cors config which needs to be set just right for the 2 to work together. This gets rid of the cors stuff in your webConfig so your only setting it in one place, in you API application code itself.
https://www.codeproject.com/Articles/1150023/Enable-Cross-origin-Resource-Sharing-CORS-in-ASP-N
Just to give a brief summary of what's in the link.
Add to project.json
//Cross Origin Resource Sharing
"Microsoft.AspNetCore.Cors": "1.0.0"
In startup add this to your ConfigureServices.
services.AddCors(
options => options.AddPolicy("AllowCors",
builder =>
{
builder
//.WithOrigins("http://localhost:4456") //AllowSpecificOrigins;
//.WithOrigins("http://localhost:4456",
"http://localhost:4457") //AllowMultipleOrigins;
.AllowAnyOrigin() //AllowAllOrigins;
//.WithMethods("GET") //AllowSpecificMethods;
//.WithMethods("GET", "PUT") //AllowSpecificMethods;
//.WithMethods("GET", "PUT", "POST") //AllowSpecificMethods;
.WithMethods("GET", "PUT",
"POST", "DELETE") //AllowSpecificMethods;
//.AllowAnyMethod() //AllowAllMethods;
//.WithHeaders("Accept", "Content-type", "Origin", "X-Custom-Header");
//AllowSpecificHeaders;
.AllowAnyHeader(); //AllowAllHeaders;
})
);
Also at it to Configure in Startup
//Enable CORS policy "AllowCors"
app.UseCors("AllowCors");
Then in your controller ensure you have these references:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using CrossOrigin.WebService.Models.DbEntities;
using Microsoft.EntityFrameworkCore;
And Finally add the attribute to your controller class.
[EnableCors("AllowCors"), Route("api/[controller]")]
public class ContactController : Controller