How to fetch data from different origin CORS? [duplicate] - javascript

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resourceā€”when trying to get data from a REST API
(26 answers)
Closed 3 years ago.
I'm trying to fetch data from a different origin to another server using Fetch API and I precise is from http to https
I can read the data from my browser but I don't know how to fetch them.
I already tried to set Access-Control-Allow-Origin to * but I still get this message :
I'm a little bit lost right know, Thank you for your support. šŸ˜
const myHeaders = new Headers({
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
});
const fetchConfig = {
method: "GET",
headers: myHeaders,
mode: "cors",
cache: "no-cache"
};
function fetchData(url) {
fetch(url, fetchConfig)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => console.error(error));
}
fetchData("https://api.example.com/");

The Access-Control-Allow-Origin header needs to be set by the server you are retrieving the data from, in response to your request.

CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.
The URL to the proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".
This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example, to avoid a direct visit from the browser.
You can simply add https://cors-anywhere.herokuapp.com/ at the beginning of your url.
Like this https://cors-anywhere.herokuapp.com/http://example.com/api/....
Check this link for more details: https://www.npmjs.com/package/cors-anywhere

Related

Need a way to enable CORS in vueJS [duplicate]

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resourceā€”when trying to get data from a REST API
(26 answers)
Closed 2 years ago.
I am new to vueJS and version using is 2.0. I need to fetch some JSON data from url. Using javacsript fetch methods to get the data from URL. below is my code,
function getValue() {
const requestOptions = {
method: "GET",
header: {"Access-Control-Allow-Origin": "GET"}
};
fetch("http://api.plos.org/search?q=title:DNA", requestOptions)
.then(
(response) => {
console.log(response.json());
}
);
}
getValue();
I am getting CORS issue like,
Access to fetch at 'http://api.plos.org/search?q=title:DNA' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I tried all the possibilities which available in stack-overflow. But no luck.
Any help would be much appreciated.
JSFiddle link - https://jsfiddle.net/m45hsekf/
Did you tried to set the mode to no-cors like the error suggests to you?
set the request's mode to 'no-cors' to fetch the resource with CORS
disabled.
I have tested it and it works:
const requestOptions = {
method: "GET",
mode: "no-cors"
};
So the request looks like this:
fetch("http://api.plos.org/search?q=title:DNA", {
mode: "no-cors"
})
.then(response => response.json())
.then(result => {
console.log(result);
});
CORS should be enabled at server level like node or java application.
Access-Control-Allow-Origin : "test-client.com" or use "*"(not recommended). Then allow this value at the server
Get is your http method not the origin value
To enable in node use this line
res. header("Access-Control-Allow-Origin", "*"); // again * is not a best practice. Please accept this as answer too
Refer to the url below for more info
https://dzone.com/articles/cors-in-node
when i have problems while i develop, i use crhome extension called CORS UNBLOCK, then i can test my api, and when i deploy to final server, always is in the same domain then i havent cors ploblem

Solving error "Request header field <name> is not allowed by Access-Control-Allow-Headers in preflight response" without access to server [duplicate]

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resourceā€”when trying to get data from a REST API
(26 answers)
Closed 2 years ago.
I'm trying to make a GET request to the url "https://public-api.wordpress.com/wpcom/v2/work-with-us" with special header 'X-future' and value 'automattician'. However, I get the error that this header is not allowed in preflight response:
"Request header field x-future is not allowed by Access-Control-Allow-Headers in preflight response."
From searching around, it seems that this is a CORS issue and I have to add the header from the server side. However, I don't have access to the server.
Is this problem not solvable or am I missing something? Here's what I wrote in code pen to test:
let url = 'https://public-api.wordpress.com/wpcom/v2/work-with-us';
const options = {
method: 'GET', //default
headers: {'X-future': 'automattician'}
};
fetch(url, options)
.then(blob => blob.json())
.then(data => console.log(data));
You can get around these cors issues by running the fetch on your own server or serverless function.
Running this in a node script will work and allow you to pass the results back to your website.
const fetch = require("node-fetch");
function fetchServer() {
return fetch("https://public-api.wordpress.com/wpcom/v2/work-with-us", {
headers: { "X-future": "automattician" }
})
.then(res => res.json())
.then(res => res);
}
You can easily deploy this using a serverless function, sometimes called lambda in AWS but most cloud providers have something similar https://aws.amazon.com/lambda/

Adding headers to fetch, solving cors, running cryptojs client side

I'm working on a project where I need first to get a authentication token from a server.
For this I need to send a GET request to the authorisation server with two key-value pairs included in the header: 1/ the client id (const) and 2/ a HMAC SHA1 calculated value based on client ID timestamp and so on.
This is working fine with Postman. (I calculate the sha1 on an online calculator)
Problem 1: (cryptojs client side)
As a node app I included the cryptojs library and the calculation works. But even with RequireJS I can not get cryptojs to run in the browser.
Error: Module name "crypto-js" has not been loaded yet for context: _. Use require([])
Problem 2: (cors)
Apparently chrome refuses the connection as the server does not accept all incoming connections.
Adding mode: 'no-cors' to the fetch request does not solve the problem.
Problem 3: (headers)
I need to add two key - value pairs to the get request headers. In postman this is no problem but I'm not sure this works with append or just adding them to my headers: { }
I constantly get a server error as if no headers where added.
I have already tried REquireJS for the cryptojs problem.
I have added the headers to a myHeaders object
const myHeaders = new Headers();
myHeaders.append('ClientID', CLIENTID);
myHeaders.append('Clientsecret', hashedToken);
and also just added the values to:
headers: {
...
'ClientID': CLIENTID,
'Clientsecret': hashedToken,
}
Both don't seem to help.
My code:
function getToken(){
hashedToken = getHashedSecret(); //this won't work client side as cryptojs can not be loaded
const CLIENTID = "CLIENTID";
const AUTHURL = "https://authorization.server.com/api/CLIENTID/authorization/";
var TIMESTAMP = getTimeStamp();
const myHeaders = new Headers();
// myHeaders.append('Content-Type', 'application/json');
myHeaders.append('ClientID', CLIENTID);
myHeaders.append('Clientsecret', hashedToken);
console.log(myHeaders);
let response = fetch(AUTHURL+TIMESTAMP, {
method: 'GET',
headers: {
myHeaders,
'Accept': 'application/json',
'Content-Type': 'application/json',
'Origin': '',
'Host': 'authorization.server.com',
include: 'ClientID', CLIENTID
},
mode: 'no-cors',
})
.then(response => response.json())
.then(data => {
console.log(data);
document.getElementById('output').innerHTML = data;
})
.catch(error => console.error(error))
console.log('data');
return data;
}
I should get a token from the server
It sounds like https://authorization.server.com doesn't allow access from your page's origin. Remember that in browsers, the Same Origin Policy prevents scripts from one origin from requesting information from other origins by default. (postman, not being a browser, is not subject to this restriction). This is so that scripts on Site A (a malicious actor) can't steal your personal information from Site B (perhaps your online banking) by making requests (from your browser, thus with your authentication information) to Site B.
For this to work, server code at https://authorization.server.com will need to respond to requests from the browser using the Cross-Origin Resource Sharing to allow access from your origin. You cannot do it from your client-side code (for obvious reasons).
Alternately, you can run a server on your origin, make the requests to that server, and it can make the requests to https://authorization.server.com and pass back the responses to you. Your server, not being a browser, is not subject to the SOP.

CORS error using fetch API - React create app

I'm consuming an API using fetch but i'm getting CORS error.
I tried multiples headers, but I'm not understading what's the problem.
I'm not the owner of the API, so I couldn't change it, but checking the response it's returning access-control-allow-origin.
Following is my request method:
export const execPOST = (url, body) => {
return fetch(url, {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
body: JSON.stringify(body)
});
};
The response is:
Request URL: http://api
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: ip
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Access-Control-Allow-Origin: *
Isn't this response above enough to allow my request?
console error:
OPTIONS http://api net::ERR_ABORTED 405 (Method Not Allowed)
Access to fetch at 'http://api' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I got this working (meanwhile I develop) using "https://cors-anywhere.herokuapp.com/", but I don't think that I should use this for production enviroment.
I found a lot of material about this problem, but nothing that worked besides implements a backend to make the request or use something else as a proxy to make the request and so on...
Update code as given below (use 'mode' with the value 'no-cors' ):
For more details follow the link => https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
export const execPOST = (url: string, body: any) => {
return fetch(url, {
mode: 'no-cors',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
};
CORS headers are set by the API to protect users from malicious code making requests to sites on their behalf.
This means that you cannot enable or disable it from the client side as the Access-Control-Allow-Origin header is a server side only header.
If you don't have access to the API to change the headers then you won't be able to use the API from the client side.
In production you would have to create your own API that will handle the requests to the API you are trying to contact.

Access-Control-Allow-Origin Error Workaround - No Access to Server

I'm getting the following error using AJAX to call an API on UPS
XMLHttpRequest cannot load https://wwwcie.ups.com/rest/Ship. 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:63786' is therefore not allowed access.
AJAX Call:
$.ajax({
url: "https://wwwcie.ups.com/rest/Ship",
type: "POST",
dataType: 'json',
crossDomain: true,
contentType: 'application/json',
data: JSON.stringify(message),
success: function (result) {
//code to execute on success
}
error: function (result) {
//code to execute on error
}
})
I have no control over the API server so I cannot modify the headers being sent back. I've tried JSONP, changing the headers I send, and a number of other solutions to no avail. I've read that making a server-side proxy could be a possible fit but I'm not sure how I would go about this. Any advice/code samples on possible solutions would be greatly appreciated. Thanks in advance.
What is to stop a malicious website from sending requests to your bank's web app and transferring all of your money? To prevent these types of shenanigans, if you're using a web browser, the server must explicitly state which remote origins are allowed to access a certain resource, if any.
If you need a key to access it, then CORS probably isn't enabled. You can always double check by looking at the response headers. See this:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
So as others have already mentioned, you can get around this by making the request from your own server (where the headers don't identify it as a browser and subject to CORS limitations), and proxy it to your client side app.
Assuming you're using Node/Express, something like this should work:
const express = require('express');
const app = express();
const myHeaders = new Headers();
const myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' };
app.get('/ups/stuff/stuff', (req, res) => {
fetch('/ups/api/stuff', myInit)
.then(response => response.json())
.then(json => res.json(json);
});
app.listen(3000);
The native fetch API is neat because you can use it on both client and server, and it supports promises like jQuery.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Categories