How to make get request to aws Api using React js - reactjs

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
});

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))
}

CORS error for golang fiber with React front-end

I am using golang fiber server, setup like this:
package main
import (
"go-auth/database"
"go-auth/routes"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
func main() {
database.Connect()
app := fiber.New()
routes.Setup(app)
app.Use(cors.New(cors.Config{
AllowHeaders: "Origin, Content-Type, Accept, Content-Length, Accept-Language, Accept-Encoding, Connection, Access-Control-Allow-Origin",
AllowOrigins: "*",
AllowCredentials: true,
AllowMethods: "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
}))
app.Listen(":3800")
}
I am calling it via React fetch:
const response = await fetch('http://127.0.0.1:3800/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name,
email,
password
})
}).then(response => response.json());
console.log(response);
Am I doing something wrong? CORS is disabled on the server side already. Here is the error I get:
Access to fetch at 'http://127.0.0.1:3800/api/register' 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.
Also this error:
register.js:17 POST http://127.0.0.1:3800/api/register net::ERR_FAILED
Found the error, hope it help someone else, literally jusst need to move routes.Setup(app) to AFTER setting CORS up, which makes sense I guess 🤦‍♂️🤦‍♂️:
func main() {
database.Connect()
app := fiber.New()
app.Use(cors.New(cors.Config{
AllowHeaders: "Origin,Content-Type,Accept,Content-Length,Accept-Language,Accept-Encoding,Connection,Access-Control-Allow-Origin",
AllowOrigins: "*",
AllowCredentials: true,
AllowMethods: "GET,POST,HEAD,PUT,DELETE,PATCH,OPTIONS",
}))
routes.Setup(app)
app.Listen(":3800")
}

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

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.

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

Failed to load https://login.microsoftonline.com/common/oauth2/v2.0/token

I'm trying to get a token using the Outlook REST API after I got the code from this url https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
I used a POST request with axios but the issue is I got this error:
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:3000' is therefore not allowed access.
My Axios post is this:
return Axios({
method: 'post',
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin':'*', Content-Type, origin, authorization, accept, client-security-token"
},
data: {
'client_id': 'xxxxxx',
'scope': 'calendars.readwrite',
'code': encodeURIComponent('000000000'),
'redirect_uri': encodeURIComponent('http://localhost:3000/storeprofile/xxxxxxxxx/outlook-scheduler'),
'grant_type': 'authorization_code',
'client_secret': encodeURIComponent('xxxxxxxxxx')
};,
responseType: 'json'
}).then((response) => {
console.log('token response: ', response);
});
I get a 200 status but can't see the token I am supposed to get in the response. The response should be a json but still nothing.
Can someone please guide me? Thank you in advance!
When you register your app, you must setup the Redirect URI/URL, usually this url will be added to the CORS header.
doc : https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview#how-do-i-get-my-app-talking-to-azure-ad-and-microsoft-graph

Resources