WordPress JSON API - Request Header Error - javascript

I'm working with the WordPress JSON API plugin to make requests to get posts and etc from my blog.
When I try to access a simple url from browser it works perfectly, but when I try to access from my Ionic application this following erros occurs:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Do I need to do something from my WP blog to allow it?

It is most likely due to a cross-origin request. So try adding the below headers in your functions.php file.
function add_cors_http_header(){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
}
add_action('init','add_cors_http_header');
Make sure that you haven't already used header in another file, or you will get a nasty error.
Hope it helps you.

Related

How to solve CORS Origin issue when trying to get data of a json file from localhost

I was trying to get the data from a json file (which is on the remote server) from localhost and I am getting error 'from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.'
Below is the code I used to send the get request.
$.ajax({
url: 'http://abc/some.json',
type: "GET",
dataType: "json",
headers: {
"Access-Control-Request-Headers": "*",
"Access-Control-Request-Method": "*",
'Content-Type':'application/json'
},
success: function (data) {
alert(data);
chatbotConfig = data;
console.log(chatbotConfig);
}
})
I am able to get the data using postman. I understand that postman is not a browser so it is not limited by CORS policy. But I am able to download the content from json file directly from the browser. Nit able to understand why I am facing issue when I tried to access from localhost. Can any one please help me to resolve this issue.
Well, the CORS error may lie in different layers of your application. Usually, by allowing all (*) origins and headers in the server-side, your problem should be fixed. But sometimes it won't and it lies somewhere else like your HTTP request header or body, DNS settings (Making sure there are no third-party DNS set in your network by yourself through the OS), or browser settings. So I will describe all of the possible solutions here shortly.
NOTE: You can read more about CORS policy here.
How to solve CORS error
If you have access to your server-side settings and/or options you need to make sure (Or if you don't you need to ask your backend developer) that everything set correctly there or not. So the steps will be as follows:
First of all, you need to make sure your server configs for CORS are set correctly.
So for example, if you are using Apache you can set the CORS policy in your .htaccess file like this (or simply check if it exists):
// This will allow all origins to access your server
Header set Access-Control-Allow-Origin "*" // You can set * to whatever domain
Header add Access-Control-Allow-Methods "*"
If you are using nodeJS you can check or set it like this:
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
If you are using Nginx you can check or set it in nginx.conf like this:
server {
location / {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "*";
}
}
If you use any other service for your server-side you should read the documentation about it, but all of them are actually same.
If you checked the above step and CORS policy was set correctly in your server-side, you may need to check your HTTP request and make sure everything is set correctly there. For example, there is no need to add these two headers
"Access-Control-Request-Headers": "*",
"Access-Control-Request-Method": "*",
in your request, because they do not exist as a header in the client-side. Wrong HTTP request API end-point address or options (like dataType), wrong HTTP request body or headers may also cause the CORS error for your here. So you need to check them all and make sure you are set them correctly.
If none of the above was the problem you can try two other approaches. I mostly encourage to use the second one if none of the above solves your problem.
Mapping your localhost to a URL using your hosts file (Usually lies under etc folder in each operating system). You can do that like this (But it's better to read the documentation for each OS).
127.0.0.1 www.test.com ## map 127.0.0.1 to www.test.com
## or
localhost www.test.com
NOTE: Usually it is better to avoid this approach.
Use browser plugins like Allow CORS.
Basically if you clearly look into the issue logs:
'from origin 'http://localhost:5000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
It's saying CORS not enabled at resource. which means it need to be fixed or allowed at server side.

How to Fix react cors error in localhost?

I'm working on a react app. Where I'm requesting for an API by AXIOS. But When I run NPM START to test my app in localhost I'm getting CORS error. Here is the error
Access to XMLHttpRequest at 'https://********.com/trx_status.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field privatekey is not allowed by Access-Control-Allow-Headers in preflight response.
I'm new in react. Please tell me how can I solve this issue. Thank you...
The error is caused by the custom privatekey header that is send to the server. This field has to be included in the Access-Control-Allow-Headers response header from the server. It can be done using:
Access-Control-Allow-Headers: privatekey
when using php the following snippet can be used:
header('Access-Control-Allow-Headers: X-Requested-With, privatekey');
This seems to me like an issue at your server side. So what you could try doing is to try adding the header "Access-Control-Allow-Origin: *".
It would be helpful if you could post it somewhere in jsfiddle or some editor so we can look at it further.
Thanks
Open package.json file, in directory of your App, then add this line (preferably under "private" line, as you can see in the picture below. This also works for any other url if your back-end is not located on your localhost.
"proxy": "http://localhost:3000/",
Remember to restart your server after this change!
For this you will need to allow CORS in your backend code for the URL you will be deploying, and you can use that URL as proxy. You can refer this documentation for detailed instructions.

Angular2 http.get preflight issues

I am currently using angular2's HTTP to POST and GET data from my custom api.
The API is in PHP and the end points etc have been tested and work fine.
The issue I am getting is any time I set the GET Authorization header, I get the following error message in Chrome console:
Response for preflight has invalid HTTP status code 404
I have set my API's headers to allow access from remote origins with the following:
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH ,DELETE");
header("Access-Control-Allow-Headers: Authorization, Content-Type");
Yes I am running my angular project on localhost, I have a POST request that happens without the Authoriazation header set and it works fine, I have also removed the Authorization header from my GET request and it then works fine (But that end point needs the Authorization header to send my JWT to my API)
Am I doing something wrong? Should I be settings other headers, I have tested the endpoint in Postman and all is working fine.
EDIT
I have also edited my Hosts file to have a tld point to my local and also one for the API which is an IP on my local machine....
So my origin is: website.com
My API: api.website.com
I have changed my
Access-Control-Allow-Origin: http://website.com:3000
I found the issue.
My router was only accepting $_POST and $_GET methods,
Chrome sends a OPTIONS method before sending the POST or GET to confirm the Origin.
For now I have just added:
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Content-Type,Accept, Origin");exit;
}
So now when a OPTION request comes through it just returns the headers that are needed to allow my POST and GET requests
The easiest way to handle this if you have control of the responding server is to add a response header for:
Access-Control-Allow-Origin: *
This will allow cross-domain Ajax. In PHP, you'll want to modify the response like so:
<?php header('Access-Control-Allow-Origin: *'); ?>
You can just put the Header set Access-Control-Allow-Origin * setting in the Apache configuration or htaccess file. It just work like a charm.
From the comments, this is an important note: the wildcard is going to allow any domain to send requests to your host. I recommend replacing the asterisk with a specific domain that you will be running scripts on. While you are going to live.
refer Origin is not allowed by Access-Control-Allow-Origin

How to resolve Access-Control-Allow-Origin error?

I know there are lot of queries already posted related to this issue. But I am still not able to resolve the error.
I am getting,
XMLHttpRequest cannot load http://localhost:100/test/test1.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
To resolve I tried following -
I used --allow-file-access-from-files --disable-web-security, while launching chrome.exe. (Not working)
I put header('Access-Control-Allow-Origin:*'); in php, after <?php tag. (Sometimes it works, but not always).
In ajax, $.ajax({crossDomain:true}) I have included. (Not working).
Add these three lines:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
There's a manual:
http://enable-cors.org/
This presents a variety of options depending your server setup (as well as explain the topic fairly well).
Note that the previous answers are totally correct for PHP... header('Access-Control-Allow-Origin:*'); if you're having problems, remember that you need to send that header before you send any body output to the buffer.
Simple solution to get this done is you need to add header to server side
header('Access-Control-Allow-Origin:*')
In one of my golang API server,I added below header code to allow CORS
Response.Header().Set("Access-Control-Allow-Origin", "*")

AngularJS allows POST or PUT to web service crossing domain?

Now, I am able to GET data from API on a web service in AngularJS using $http or $resource but I cannot POST or PUT date to update API on the same web service.
The error I got is the cross-origin issue which is:
XMLHttpRequest cannot load http://rm.ws.localhost.dev/bookings/36.json. Origin http://rm.localhost.dev is not allowed by Access-Control-Allow-Origin.
In Angular, the code as follow enables to "GET" data,
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
In addition, I changed configure file on web service server, added two lines:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
All these make me access web service by GET data, cannot PUT or POST. Where I went wrong or I miss something. I thought Angular supports POST and PUT. Thanks all.
My guess is that the API/web service server is not handling an OPTIONS request. A cross-origin PUT will always result in the browser "preflighting" the request (via an OPTIONS request) first. A cross-origin POST with non-simple headers will also be preflighted in this manner. The server must acknowledge the underlying method and the underlying non-simple headers (as well as the Origin) in the response to the OPTIONS request. Please note that cross-origin PUT and non-simple POSTs will never work in IE9 or older, as cross-origin ajax requests must be made with XDomainRequest in those browsers, which does not support preflighting.

Categories

Resources