Fetch http://localhost:3001/ from Chrome Extension with React - reactjs

I have seen some similar problems and solutions where people want to hit http://localhost:3001/some_url and use cors to do so.
But my problem is a little different. My web app is not a website but a web-extension.
SO far I cannot find a way to fetch from http://localhost:3001/url even with using cors.
What I have tried is:
Server:
const cors = require("cors");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(
cors({
origin: "http://localhost:3001/url" // restrict calls to those this address
})
);
In background.js file:
create(urls){
console.log(urls);
return new Promise((resolve, reject) =>{
fetch('https://cors-anywhere.herokuapp.com/'+'http://localhost:3001/url', {
method: 'POST',
body: JSON.stringify(urls),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
"Access-Control-Allow-Origin: *"
}
})
.then(result => result.json())
.then(json => resolve(json))
.catch(err => {
console.log(err);
reject(err);
});
});
}
I have also added "proxy": "http://localhost:3001/url" in packages.json.
I am still getting the error:
Access to fetch at 'http://localhost:3001/url' from origin 'chrome-extension://extension_id' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3001/url' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Is there any way to solve the issue?

It looks like you're adding a path /url to the origin, but an origin is:
Web content's origin is defined by the scheme (protocol), host
(domain), and port of the URL used to access it
Try using http://localhost:3001 as the origin value.

Related

Cors Error When I do a redirect from the server

I have a server running on localhost:8090, which I make a request to from a React App running on localhost:3000 . The aim of this request is to perform some operations and when it is done, it does a redirect to https://www.google.com/ from the backend. This is what it looks like.
Frontend:
function processReq() {
fetch(`http://localhost:8090/some-process`,
{
method: "GET",
headers: {
Accept: "application/json",
}
}
)
.then(response => {
console.log(response);
}).catch(err => console.log(err))
}
Backend
r.GET("/some-process", handlers.DoProcess)
func DoProcess(c *gin.Context) {
// processes request
var w http.ResponseWriter = c.Writer
http.Redirect(w, c.Request, "https://www.google.com", http.StatusSeeOther)
}
All of these works well, but I get a Cors error that looks like this
Access to fetch at 'https://www.google.com/' (redirected from 'http://localhost:8090/some-process') from origin 'http://localhost:3000' 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.
Mind you, I have setup cors on my backend and it looks something like this
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
if c.Request.Method == "OPTIONS" {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Accept, Origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
c.AbortWithStatus(204)
return
}
c.Next()
}
}```
Your situation is similar to the one described in the answer to Mongoose redirect not waiting for findByIDAndDelete.
Instead of letting the server respond with a redirect, let it respond with 200 OK and have the client execute
location.href = "https://www.google.com";
when it receives this response.
The reason you're seeing cors errors is because google is not returning permissible access control headers.
The more fundamental issue is you're trying to redirect the browser as part of a fetch request which won't work; if google did allow cross origin access, you would just be returning the HTML response in your fetch call which isn't that useful.
Instead, you should just return a 200 in your server response and have the client redirect the browser window to google.
function processReq() {
fetch(`http://localhost:8090/some-process`,
{
method: "GET",
headers: {
Accept: "application/json",
}
}
)
.then(response => {
console.log(response);
window.location.href = 'https://google.com';
}).catch(err => console.log(err))
}

Cannot fetch from localhost with Authorization header

I'm having a hard time sending a get request to my expressjs backend with the fetch method.
fetch('http://localhost:9000', { method: 'GET', headers: { Authorization: `Bearer ${accessToken.accessToken}` }}).then(() => {
debugger
}).catch((error) => {
debugger
})
Based on what I could read, this seems correct - The request is however not reaching the API.
I tried constructing the options object like so, without any luck:
const options = {
method: "GET",
headers: headers
};
Without the headers, my request reaches the API. Anyway, the error that I'm getting is this:
error: TypeError: Failed to fetch
If you make that request from an origin other than http://localhost:9000, the Authorization header will cause the browser to make a CORS preflight request OPTIONS http://localhost:9000 before the GET request, and if that fails, the GET request would not be made.
You must ensure that your server handles the preflight, e.g., through the cors middleware.
So I found a solution, basically I added this middleware in my Express application to allow CORS,
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "*");
res.header("Access-Control-Allow-Methods", "*");
next();
});

I'm getting CORS error: Request header field content-type is not allowed by Access-Control-Allow-Headers

I have a Node/Express backend and React frontend. When I'm trying to send post request through axios from my react app to the backend, I get an error:
Access to XMLHttpRequest at
'http://localhost:5000/api/user/create-account' from origin
'http://localhost:3000' has been blocked by CORS policy: Request
header field content-type is not allowed by
Access-Control-Allow-Headers in preflight response.
But, I'm using res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); Still, I'm getting that error.
Here's the server side code:
const cors = require("cors");
const app = express();
let corsOptions = {
origin: 'http://localhost:3000',
optionsSuccessStatus: 200 ,
credentials: true
};
app.use(cors(corsOptions));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Content-Type', 'application/json;charset=UTF-8');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
And, this is how I'm making POST request from my frontend:
axios.post("http://localhost:5000/api/user/create-account", data, { withCredentials: true } )
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
P.S: I know there are similar questions on here but I have followed their answers but my problem isn't solved that's why I'm asking this question.

Api call cause error 'Access-Control-Allow-Origin' header is present on the requested resource

I am trying to call an api but it is giving me following error :
Access to fetch at 'https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am using react and the code is :
try {
let url = `https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01`;
let response = await fetch(url,{
mode: 'cors', // no-cors,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
"Accept": 'application/json',
'Origin' : 'http://localhost:3000'
//'Content-Type': 'text/xml'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
});
this.setState(() => {
return {
searchResults : response
}
})
} catch (error) {
console.error(error);
}
please guide what to do
The error is due to CORS, there is nothing wrong with the front-end code.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses
additional HTTP headers to tell browsers to give a web application
running at one origin, access to selected resources from a different
origin.
To fix this issue, the server should set the CORS headers,
See here on how to enable CORS for your server
If your server is running express you need to set cors like this,
app.use(function(req, res, next) {
// update to match the domain you will make the request from
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
or use the cors middleware for express

How to make get request to aws Api using React js

I have make request to aws api with get method using React js But it shows error :-
"Access to fetch at 'https://blahblah.com/dev/getControllist' from origin 'http://test.com:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response."
But If I hit same api direct to browser or using postman it returns json successfully. Please help me if anyone knows.
My code is:-
var uri = "blahblah.com/dev/getControllist";
let h = new Headers({
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Credentials": true,
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
"Access-Control-Request-Headers": "Origin, X-Requested-With, Content-Type, Accept,x-access-token"
});
let request = new Request(uri,
{
method: 'GET',
headers: h,
cors:true
});
fetch(request)
.then((result) => {
// Get the result
// If we want text, call result.text()
return result.json();
}).then((jsonResult) => {
// Do something with the result
console.log(jsonResult);
this.setState({
items: jsonResult
});

Resources