Alright I really hate it when it has this error in the console. And I know that stackoverflow is flooded with these types of questions. However, I've done the research and I have CORS enabled in my Web API 2 web service and I'm still getting this error.
This is my Web API 2 code:
namespace WebApi.App.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ServiceController : ApiController
{
[HttpGet]
[Route("GetData")]
public IHttpActionResult GetEmpData(DATAvars theDATA)
{
return Ok("WORKED! " + theDATA);
}
[HttpPost]
[Route("PostData")]
public IHttpActionResult PostEmpData(DATAvars theDATA)
{
return Ok("WORKED! " + theDATA.theID);
}
}
public class DATAvars
{
public string theID { get; set; }
public string empImg { get; set; }
}
}
AND
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
AND
namespace WebApi.App
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.MapHttpAttributeRoutes();
config.EnableCors();
}
}
}
AND
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}
Then for my AJAX call code (which is being hosted on another domain):
$.ajax({
type: "POST",
crossDomain: true,
url: "http://dev-blahblah/newWS/PostData",
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
},
data: {
theID: "2135648792",
empImg: "false"
},
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
}
});
And this is the error in the console:
The Console Network says:
Failed to load resource: the server responded with a status of 404 (Not Found)
index.html:1 XMLHttpRequest cannot load http://dev-blahblah/newWS/PostData. Response for preflight has invalid HTTP status code 404
And now this is the SAME request but in POSTMAN:
I've spent DAYS trying to figure this out and endless googleing to find examples, I have, but seems like all the examples do not work.
I would be very grateful for someone to let me know what I need to do in order to get this working with JQUERY AJAX.
-Running it on the same domain in CHROME = WORKS
-Running it on a different domain in CHROME = DOES NOT WORK
-Running it on the same domain in IE = WORKS
-Running it on a different domain in IE = WORKS
Used the following config section in my web API web.config file to avoid the 404 error.
<handlers>
<remove name="WebDAV"/>
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
</handlers>
Removing WebDAV did not work for me as there might be a global policy on my server. This, however, cut it:
<system.webServer>
<security>
<requestFiltering>
<verbs applyToWebDAV="false">
<add verb="DELETE" allowed="true" />
<add verb="PUT" allowed="true" />
<add verb="OPTIONS" allowed="true" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
It was <add verb="OPTIONS" allowed="true" /> that made the difference.
Related
When I send an ajax request to the server, I want to return an individual message to the client in the responseText in case of an error. In debug mode on my development machine this works fine. Unfortunately, in production mode on the web server I always get an error message "Bad Request" but no longer the individual message. I am developing my application in ASP.NET MVC 5 and I am using jQuery 3.6.0.
My ajax request looks like this:
$.ajax({
type: 'POST',
url: 'myURL',
data: {
val1: clientVal1,
val2: clientVal2
},
success: function (res) {
//do smthg...
},
error: function (response) {
alert(response.responseText);
}
});
On the server side, I take the ajax call like this:
[HttpPost]
public ActionResult myURL(string val1, string val2)
{
if(val1.contains(val2))
{
}
else
{
Response.StatusCode = 400;
Response.Write("My custom error msg.");
return new HttpStatusCodeResult(400);
}
return Json(new { someVal1, otherVal2}, JsonRequestBehavior.AllowGet);
}
The httperrors in my webconfig file look like this:
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="403" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="404" path="/ErrorHandling/http404" responseMode="ExecuteURL" />
<error statusCode="403" path="/ErrorHandling/http403" responseMode="ExecuteURL" />
<error statusCode="500" path="/ErrorHandling/http500" responseMode="ExecuteURL" />
</httpErrors>
What am I doing wrong?
I have found the solution. First I had to move the redirection to the individual error pages in the web.config to the <system.web> area. Now my system.web area looks like this ([...] means that there are other settings which are not relevant for this):
<system.web>
[...]
<customErrors mode="On" redirectMode="ResponseRedirect" defaultRedirect="/ErrorHandling/http500">
<error statusCode="404" redirect="/ErrorHandling/http404" />
<error statusCode="403" redirect="/ErrorHandling/http403" />
<error statusCode="500" redirect="/ErrorHandling/http500" />
</customErrors>
[...]
</system.web>
After that, I had to change the system.webServer section as suggested in the post by freedomn-m and suggested by Rahul Sharam as follows:
<httpErrors errorMode="Custom" existingResponse="PassThrough">
</httpErrors>
Now everything works as it should.
Hi I'm posting to a wcf service from javascript. I can post a single parameter (string, blob, int) fine, but when I try to put the data in a class I get a 400 Bad Request error. I've tried both Bare and Wrapped for my BodyStyle, but get the same error for each. Any ideas what could be happening?
Thanks
Pete
C# Data Contract:
[DataContract]
public class TestData
{
[DataMember]
public string SubmissionID { get; set; }
}
C# Interface:
[OperationContract(Name = "Upload")]
[DataContractFormat]
[WebInvoke(Method = "POST",
UriTemplate = "Upload/",
BodyStyle = WebMessageBodyStyle.Wrapped,//Bare gives same error
ResponseFormat = WebMessageFormat.Json)]
String Upload(TestData ps);
C# Service Method:
public String Upload(TestData ps)
{
....
return "Submission Complete";
}
Javascript call:
var TestData = {SubmissionID: "1" };
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:59070/WCFUploader.svc/Upload/', true);
xhr.send(TestData);//400 Bad Request
C# Web Config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.serviceModel>
<services>
<service name="PhotoUploadServiceTest.WCFUploader" behaviorConfiguration="defaultServiceBehavior">
<endpoint address="" binding="webHttpBinding" behaviorConfiguration="defaultEndpointBehavior"
contract="PhotoUploadServiceTest.IWCFUploader" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
transferMode="Streamed"
sendTimeout="00:05:00">
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="defaultEndpointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="defaultServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
The problem was in my javascript call. I needed to set the content of the request header to "application/json" and needed to create a String serial of the object before I sent it -- used dojo.toJson from the dojo library:
var TestData = {SubmissionID: "1" };
xhr.setRequestHeader("Content-type", "application/json");
var xhr = new XMLHttpRequest();
xhr.open('POST',
'http://localhost:59070/WCFUploader.svc/Upload/', true);
xhr.send(dojo.toJson(TestData));//this worked!!
I have created ASP.NET WebAPI with the following POST method:
[HttpPost, Route("")]
public IHttpActionResult Post([FromBody] StudentDto student)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var maxId = conrollerStudents.Max(x => x.ID);
student.ID = ++maxId;
conrollerStudents.Add(student);
InsertStudentIntoDatabase(student);
return CreatedAtRoute("GetStudent", new { id = student.ID }, student);
}
WebAPI's config:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
This API method works only in POSTMAN where I got 201 as result of the POST request. When I move this request into JavaScript-Jquery-AJAX with the following code (auto-generated by POSTMAN). I get the following error message:
{
"Message":"No HTTP resource was found that matches the request URI 'http://localhost:59523/api/students'.",
"MessageDetail":"No action was found on the controller 'Students' that matches the request."
}
This is the auto-generated JavaScript-Jquery-AJAX Code, which happens to do not work:
// ...
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:59523/api/students",
"method": "POST",
"headers": {
"content-type": "application/json"
},
"processData": false,
"data": "{\n \"FirstName\": \"Sample\",\n \"LastName\": \"Sample\",\n \"City\": \"Sample\",\n \"ListOfCourses\": []\n}"
};
$.ajax(settings).done(function (response) {
console.log(response);
});
// ...
Any idea why this happens?
It looks like you want the method to be the default action on that controller, try setting the default action to Index and renaming your method as Index.
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
This problem relates to the incorrect WebAPI configuration file: Web.config. I have changed the system.webServer section to:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH" modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH" type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
</system.webServer>
I'm trying to save an html5 canvas content, to localhost by using a webserver.
I'm getting the canvas value in base64 and I send it to my webservice.
But when I send the data to the webservice I get this error and the file is not saved:
415: "Cannot process the message because the content type
'application/octet-stream' was not the expected type 'text/xml;
charset=utf-8'."
What am I doing wrong?
Service.vb
Imports System.IO
Imports System.Drawing
Public Class Service
Implements IService
Public Sub New()
End Sub
Public Function savePictureBase64(bytes As Byte()) As Boolean Implements IService.savePictureBase64
Dim fullOutputPath As String = "c:\temp\file.png"
'get a temp image from bytes, instead of loading from disk
'data:image/gif;base64,
Dim imagem As Image
Using ms As New MemoryStream(bytes)
imagem = Image.FromStream(ms)
End Using
File.WriteAllBytes(fullOutputPath, (bytes))
Return True
End Function
End Class
IService.vb
<ServiceContract()>
Public Interface IService
<OperationContract()>
Function savePictureBase64(bytes As Byte()) As Boolean
' TODO: Add your service operations here
End Interface
Javascript
function save () {
var image = document.getElementById("sketchpad").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: 'http://localhost:52193/service.svc',
data: image,
contentType: 'application/octet-stream',
success: function (msg) {
alert('Image saved successfully !');
},
error: function(result) {
alert("Error");
}
});
}
</script>
web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
<pages>
<namespaces>
<add namespace="System.Runtime.Serialization"/>
<add namespace="System.ServiceModel"/>
<add namespace="System.ServiceModel.Web"/>
</namespaces>
</pages>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding messageEncoding="Mtom">
</binding>
</basicHttpBinding>
</bindings>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
The error is the call that you made by Javascript code. You try to send a string, the webservice expected an XML message:
expected type 'text/xml; charset=utf-8'.
I don't know how complicated it is to compose a webservice XML message from Javascript, but I think that you can change your approach. Your service is hosted under IIS, can you build an HttpHandler?
public class UploadBase64 : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string image_string = string.Empty;
using (StreamReader sr = new StreamReader(context.Request.InputStream))
image_string = sr.ReadToEnd();
byte[] image_bin = Convert.FromBase64String(image_string);
File.WriteAllBytes(#"c:\temp_10\test01.png", image_bin);
}
}
...and add this to your web.config file:
<system.web>
<httpHandlers>
<add verb="POST" path="UploadBase64.aspx" type="WebApplication1.UploadBase64"/>
</httpHandlers>
</system.web>
I created an mvc4 web api project using vS2012. I used following tutorial to solve the Cross-Origin Resource Sharing, "http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api-rc-version.aspx". It is working successfully, and i post data from client side to server successfully.
After that for implementing Autherization in my project, I used the following tutorial to implement OAuth2, "http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for-mvc-two-legged-implementation.aspx". This is help me for getting RequestToken on client side.
But when i post data from client side, i got the error,
"XMLHttpRequest cannot load http://. Request header field Content-Type is not allowed by Access-Control-Allow-Headers."
My client side code look like,
function PostLogin() {
var Emp = {};
Emp.UserName = $("#txtUserName").val();
var pass = $("#txtPassword").val();
var hash = $.sha1(RequestToken + pass);
$('#txtPassword').val(hash);
Emp.Password= hash;
Emp.RequestToken=RequestToken;
var createurl = "http://localhost:54/api/Login";
$.ajax({
type: "POST",
url: createurl,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Emp),
statusCode: {
200: function () {
$("#txtmsg").val("done");
toastr.success('Success.', '');
}
},
error:
function (res) {
toastr.error('Error.', 'sorry either your username of password was incorrect.');
}
});
};
My api controller look like,
[AllowAnonymous]
[HttpPost]
public LoginModelOAuth PostLogin([FromBody]LoginModelOAuth model)
{
var accessResponse = OAuthServiceBase.Instance.AccessToken(model.RequestToken, "User", model.Username, model.Password, model.RememberMe);
if (!accessResponse.Success)
{
OAuthServiceBase.Instance.UnauthorizeToken(model.RequestToken);
var requestResponse = OAuthServiceBase.Instance.RequestToken();
model.ErrorMessage = "Invalid Credentials";
return model;
}
else
{
// to do return accessResponse
return model;
}
}
My webconfig file look like,
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oauth" type="MillionNodes.Configuration.OAuthSection, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
<section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
</sectionGroup>
</configSections>
<oauth defaultProvider="DemoProvider" defaultService="DemoService">
<providers>
<add name="DemoProvider" type="MillionNodes.OAuth.DemoProvider, MillionNodes" />
</providers>
<services>
<add name="DemoService" type="MillionNodes.OAuth.DemoService, MillionNodes" />
</services>
</oauth>
<system.web>
<httpModules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
</httpModules>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral" preCondition="" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
<dotNetOpenAuth>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
As hinted at by this post Error in chrome: Content-Type is not allowed by Access-Control-Allow-Headers just add the additional header to your web.config like so...
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin to *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
Make sure that you haven't already used header in another file, or you will get a nasty error. See the docs for more.
I know it's an old thread I worked with above answer and had to add:
header('Access-Control-Allow-Methods: GET, POST, PUT');
So my header looks like:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
And the problem was fixed.
For Nginx, the only thing that worked for me was adding this header:
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
Along with the Access-Control-Allow-Origin header:
add_header 'Access-Control-Allow-Origin' '*';
Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.
Had the same problem, while differently from other answers in my case I use ASP.NET to develop the WebAPI server.
I already had Corps allowed and it worked for GET requests. To make POST requests work I needed to add 'AllowAnyHeader()' and 'AllowAnyMethod()' options to the list of Corp options.
Here are essential parts of related functions in Start class look like:
ConfigureServices method:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});
Configure method:
app.UseCors(MyAllowSpecificOrigins);
Found this from:
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
https://forums.asp.net/t/2168883.aspx?Request+header+field+content+type+is+not+allowed+by+Access+Control+Allow+Headers+in+preflight+response+