Frontend gets Error 401 from Backend in CORS request - apache/php insufficiently configured? - javascript

I have a frontend, running on most recent vue on port 5000.
Then I have my backend, running on most recent lumen on port 8080.
Both are on my localmachine. Later in production, they will be separated on two virtual machines.
Right now, when sending an http request from the frontend to the backend, I get the following error to my devConsole (NOT the vue devtools, but the usual firefox/chrome devtools console!):
Error: Request failed with status code 401
The function returning the axios object executing the http request looks like this:
function fetchData(method, slug, payload) {
return axios[method](`${API_ENDPOINT}${slug}`, payload);
}
The call looks like this:
fetchData(METHOD_POST, USER_LIST, "someToken").then((res)=>{
return res
})
METHOD_POST contains the string post and USER_LIST contains the string /user/show_data which is used to further specify the URL. In my Lumen backend, it accesses the following route:
$router->group(['prefix' => 'user', 'middleware' => 'auth'], function() use ($router){
$router->post('/show_data', 'UserController#getData');
});
The route and the respective controller work, I've tested it with RESTClient https://addons.mozilla.org/de/firefox/addon/restclient/
I think that syntaxwise, everything is fine. Also, the token wasnt expired when I used it, I checked this multiple times.
So I think that it might be connected to the CORS-Policy of the apache and/or php.
Im running apache and php from the latest XAMPP dist.
Still, I'm not entirely sure if thats it, especially since this is the first time that I connect a backend using lumen and a frontend using vue.js.
EDIT: I managed to activate "withCredentials" for my axios object by changing the function body to:
axios.defaults.headers.withCredentials = true;
return axios[method](`${API_ENDPOINT}${slug}`, payload);
However, now the CORS problem turns up ^^
When sending the http request, I get these error messages to my console:
Access to XMLHttpRequest at 'http://localhost:8080/user/show_data' 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.
And
xhr.js:178 POST http://localhost:8080/user/show_data net::ERR_FAILED
And
createError.js:16 Uncaught (in promise) Error: Network Error
at t.exports (createError.js:16)
at XMLHttpRequest.d.onerror (xhr.js:83)
What should I do?
EDIT2:
I now added the following lines to my httpd.conf and restarted apache and lumenproject:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Max-Age: 360
Header set Access-Control-Allow-Credentials: true
Header set Access-Control-Allow-Methods: *
Header set Access-Control-Allow-Headers: Origin
Header set Access-Control-Expose-Headers: Access-Control-Allow-Origin
</IfModule>
I also tried out explicitely specifying the origin to
http://localhost:8080
and
http://localhost:5000
But it didnt help. The errormessage remains the same.

Most browser will block you anyway if your backend allow any host.
Access-Control-Allow-Origin "*"
You are also missin a semi-colon
Access-Control-Allow-Origin: "*"
Try
Access-Control-Allow-Origin: "yourorigindomain.com"

Related

how to add access control allow origin header in simple angular post request? [duplicate]

I have a Vue application generated with webpack-simple option. I am trying to make a GET request to https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en but I get the error:
XMLHttpRequest cannot load
https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:8080' is therefore not allowed
access.
I am using vue-resource and have added:
Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'
That has no effect.
I also added this in the devServer option in the webpack.config.js:
devServer: {
historyApiFallback: true,
noInfo: true,
headers: {
"Access-Control-Allow-Origin": "*"
}
}
That isn't solving the problem either; the error message remains the same.
How to go about solving this?
Access-Control-Allow-Origin is a response header the responding server must send.
And all other Access-Control-Allow-* headers are response headers for servers to send.
If you don’t control the server your request is sent to, and the problem with the response is just the lack of the Access-Control-Allow-Origin header or other Access-Control-Allow-* headers you can still get things to work—by making the request through a CORS proxy.
You can easily run your own proxy using code from https://github.com/Rob--W/cors-anywhere/.
You can also easily deploy your own proxy to Heroku in just 2-3 minutes, with 5 commands:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
After running those commands, you’ll end up with your own CORS Anywhere server running at, e.g., https://cryptic-headland-94862.herokuapp.com/.
Now, prefix your request URL with the URL for your proxy:
https://cryptic-headland-94862.herokuapp.com/https://example.com
Adding the proxy URL as a prefix causes the request to get made through your proxy, which:
Forwards the request to https://example.com.
Receives the response from https://example.com.
Adds the Access-Control-Allow-Origin header to the response.
Passes that response, with that added header, back to the requesting frontend code.
The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.
This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS request, because in that case, the proxy also sends back the Access-Control-Allow-Headers and Access-Control-Allow-Methods headers needed to make the preflight successful.
And if you have frontend code that adds the Access-Control-Allow-Origin header or other Access-Control-Allow-* headers to the request, remove that code — because the only effect you have by adding those request headers is, you’re triggering your browser to send a CORS preflight OPTIONS request rather than the actual GET or POST request in your code.
Ok, this answer is not really related to the question but it can be useful for those, who can't touch API server side, use free to use proxy service from Rob--W
function doCORSRequest(appUrl) {
const cors_api_url = 'https://cors-anywhere.herokuapp.com/';
let nUrl = cors_api_url + appUrl;
fetch(nUrl)
.then(response => {
if(response.status !== 200) {
alert("Error :( try later.")
return;
}
response.json()
.then(data => showResult(data))
})
}
doCORSRequest(yourURL);

How to fix blocked redirect due to CORS issues?

Here is my setup:
Running a local angular application on port 4200
Running an API using Deno on port 4300.
I have a use case where a client call at some api endpoint http://localhost:4300/foo, needs to redirect the user to another portion of the front end, say http://localhost:4200/bar#baz.
Currently this fails with the following error:
Access to XMLHttpRequest at 'http://localhost:4200/bar#baz' (redirected from 'http://localhost:4300/foo') from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
I have tried disabling/allowing cors on the API:
ctx.response.headers.set('Acces-Control-Allow-Origin','*');
ctx.response.headers.set('Acces-Control-Allow-Headers','*');
ctx.response.headers.set('Acces-Control-Allow-Methods','*');
ctx.response.headers.set('Access-Control-Allow-Credentials','true');
But this does not work.
Any ideas on how to fix this? Without setting up a proxy or installing a browser plugin.
Thanks!
See MDN:
The value "*" only counts as a special wildcard value for requests without credentials (requests without HTTP cookies or HTTP authentication information). In requests with credentials, it is treated as the literal header name "*" without special semantics. Note that the Authorization header can't be wildcarded and always needs to be listed explicitly.
You are making a request with credentials therefore you can't use * as a wildcard and have to be explicit about which headers you are using.

Window exe API cors issue when calling from any webapp. C++

We've created one EXE file using the CPP language and create one API like http://localhost:5800/get-id/. when I open in browser return me the perfect output.
When I used fetch in HTML > script page, then getting No "Access-Control-Allow-Origin" header is present on the requested resource.
Code1:
fetch("http://localhost:5800/get-id/", {method: 'GET').then(function(response) {
console.log(response.text());
}).catch(function(error) {
console.log('Request failed', error)
});
After research, I've added the mode: no-cors error lost but getting an empty response.
Code2:
fetch("http://localhost:5800/get-id/", {method: 'GET', mode: 'no-cors'}).then(function(response) {
console.log(response.text());
}).catch(function(error) {
console.log('Request failed', error)
});
If I use code2 in any inspect console then getting an empty body but when I open http://localhost:5800/get-id/ in the browser and try to hit code2 in the console then getting the perfect parameter.
It means, localhost domain it's working fine but when it's fetched from any domain through my error.
What is the proper solution for it? In C/CPP language how can we allow cors?
Strange:
when I hit from console, it's show me empty
For same request I checked network tab, show 200 OK with proper response / preview data
CORS is a complex topic, I usually use CORS middleware to handle it in Node.JS in Express server (maybe the code will be useful to solve this).
It's goal is to allow API on domain api-domain to list web applications that can use it, for example your application is on webapp-domain domain.
When application calls fetch('http://api-domain/get-id/') to another domain it is referred to as cross-origin call.
All browser do CORS preflight call like this to check for allowance:
OPTIONS /get-id/
Access-Control-Request-Method: GET
Access-Control-Request-Headers: origin, x-requested-with
Origin: http://webapp-domain
(please note it's an OPTION request to the API, not GET)
And response should list webapp-domain as allowed (and specify which HTTP methods are allowed)
HTTP/1.1 204 No Content
Connection: keep-alive
Access-Control-Allow-Origin: http://webapp-domain
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Max-Age: 86400
After the successful preflight call like this the browser will continue with fetch, for example, it will send GET request to http://api-domain/get-id/
P.S.
One of the ways to skip CORS is to set HTTP proxy in webapp-domain which will call api-domain on server-side and is not limited by CORS. See this answer for details.

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.

need to make a cors request from localhost - standard solutions don't seem to work as expected

I need to make a CORS request from localhost. I have the Allow-Control-Allow-Origin Chrome plugin installed and turned on and when I hover over the menu item it shows: "Allow-Control-Allow-Origin: *". I created a .bat file with the following contents:
start chrome http://localhost:8080/MyPage.html --disable-web-security --user-data-di
This opens a new Chrome instance at the expected url but the CORS request still fails with the following error:
Failed to load [rest-url]: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Can you recommend any workarounds for this?
could you show the code and give us some more information about the technology etc. which you are using?
It seems like you´re not sending a "preflight"-Request, your preflight-request does not contain the needed headers or your remote does not return the right headers:
For example, suppose the browser makes a request with the following headers:
Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header
Your server should then respond with the following headers:
Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header
Credits to: #monsur
See also: CORS - How do 'preflight' an httprequest?
the Access-Control-Request-Headers needs to contain all custom headers your sending allong with the real request, it will fail if not. At least for me, the error messages are somewhat cryptic and don´t always point in the right direction.

Categories

Resources