CORS policy problem in react js client side - javascript

I created a Formik login form and call to react js fetch method. Add cors in web api end and successfully run in Postman and jquery. How to call "token_type": "bearer", through react js? cors is also enabled in web api and also generate Token successfully. How to call this url https://localhost:44323/token through react js?
My code is
onSubmit={(values) => {
fetch('https://localhost:44323/token', {
method: 'POST',
header: { 'Content-type': 'application/json,multipart/form-data' },
data: JSON.stringify(values)
})
.then(r => r.json())
.then(res => {
console.log(res)
});
}}>
Error messages

The root cause of the problem can be found in the following error message shown:
"Access to fetch at https://localhost:44323/token from origin http://localhost:3000 has been blocked by CORS policy. No Access-Control-Allow-Origin header is present on the requested resource ...."
How to fix the problem?
The problem can be fixed in these ways:
1. Allow the origin (http://localhost:3000) on the server (Recommended)
This can be done by adding the following header to HTTP response on the server side:
Access-Control-Allow-Origin: http://localhost:3000
2. Send Fetch request in the 'no-cors' mode
This can be done by updating the fetch request as follows:
fetch( 'https://localhost:44323/token',
{
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}
)
.then(response => {
// Code for processing the response
}
)
.catch((error) => {
// Code for handling the error
}
)
More information:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Related

Failed to fetch error when using fetch API in office scripts

I am trying to run a post request from office scripts on an api, but kept getting a failed to fetch error each time when I add :
"Content-type": "application/json"
to the header, once I remove the content-type option or replace its value with something other than "application/json" , then the fetch request works , but returns an error with code 0 and validation error messages indicating that the userName and password ('which are already defined in the body could not be found'):
Below is the code
async function main(workbook: ExcelScript.Workbook) {
const param = {
method: "POST",
headers: {
//"Content-type": "application/json"
},
body: JSON.stringify({ user_id: "uname", password: "pwd"})
};
await fetch("https://testAPI/login/", param).then(response => response.json())
.then(data => console.log(data));
}
error when I run this code with Content-Type header set to 'application/json' (line 33 contains the fetch instruction ):
Line 33: Failed to fetch
Error when I run this code with content-Type set to 'text/plain', other options or completely removing the content-type property from the header :
Also , this same request from postman or power automate with header content-type set to 'application/json' runs successfully , the issue happens only in office script
The issue could potentially have to do with CORS. I had to include CORS headers on the API endpoint I was trying to hit. This may be the issue since you said the status code of the response was 0. Why fetch return a response with status = 0?
I added the following headers to the API route:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-For
Here is my OfficeScript code for reference:
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(cellData),
headers: {
'Content-Type': 'application/json'
}
})

Request failed with status code 403 - magiceden api with axios

Please help me, I'm so stuck on this problem: I'm making a request magiceden.io API with Axios on Javascript and the request is not working (Request failed with status code 403).
My URL request: https://api-mainnet.magiceden.io/new_collections
My code:
axios.get("https://api-mainnet.magiceden.io/new_collections", {
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"User-Agent": "Mozilla/5.0",
},
}).then((res) => {
console.log(res.data);
}).catch((err) => {
console.log(err.message);
});
Status 403 means that the request is a forbidden access. It is probably because MagicEden now uses Cloudflare protection which restricts access. You can try changing your request headers which can bypass the cloudflare protection.

GetResponse Api integration Using fetch() is not working

GetResponse Api integration Using Fetch API method not working
The following SMS is showing in the console:
Cross-Origin Request Blocked:
The Same Origin Policy disallows reading the remote resource at https://api.getresponse.com/v3/contacts.
(Reason: CORS header 'Access-Control-Allow-Origin' missing).
Code is given bellow:
// main.js
// POST request using fetch()
fetch("https://api.getresponse.com/v3/contacts", {
// Adding method type
method: "POST",
// Adding body or contents to send
body: JSON.stringify(
{
campaign : {
campaignId: "5D8Qm"
},
name: "xyz",
email: "fdfdfd#gmail.com"
}
),
// Adding headers to the request
headers: {
"X-Auth-Token": "api-key o9q5s264jbp9dws0nsevnagqdst81esh",
"Content-type": "application/json"
}
})
// Converting to JSON
.then(response => response.json())
// Displaying results to console
.then(json => console.log(json));
It's a classic CORS issue as azbarcea said.
As for your comment about why cURL works but Fetch API not, you can refer to this answer in Stack Overflow.

Using SpreadShirt REST API with JavaScript / Fetch

What i try to do
I have a small ReactJS application. In this application, i try to do an REST request to the API of SpreadShirt via the JS Fetch API.
What fails
Basically i get no data. The console of the browser shows the following output:
Access to fetch at 'https://api.spreadshirt.net/api/v1/shops/100749149/sellables?mediaType=json' 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.
My Code
getData() {
const header = new Headers({
"Authorization": "SprdAuth apiKey=\"XXXXXXXXX"",
"User-Agent": "MukoSoft/1.0 (https://mydomain.de; my#mail.de)"
});
const options = {
method: 'GET',
headers: header
};
fetch('https://api.spreadshirt.net/api/v1/shops/100749149/sellables?mediaType=json', options)
.then(response => response.json())
.then(data => this.setState({ data: data }))
.then(() => this.setState({ loading: false }))
}
Does anyone has a hint for me, while i can't fetch via JavaScript? And can somebody explain, why the request via Postman works, but not via fetch API?
Since this is my first question on stack overflow, you can give me advices on how to formulate questions better

react + redux - 401 - unauthorized - missing headers in Request Headers

return fetch(`{SERVICE API URL}`, {
method: 'GET',
headers: {
'userName': "username",
'password': "password",
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
I'm trying to get service API data with authorization headers, but getting 401 - Unauthorized error and the response is Missing Request Headers.
Tried with sending authorization content with body also - getting same error 401 - Unauthorized error.
Edited:
headers: {
'userName': "xyz",
'sessionToken': "xyz................."
}
When I'm checking with Postman client it is working fine, but not with the redux-saga fetch method. Kindly help me for this.
Looks like it's a backend problem - CORS Filter configuration
If the backend is on a different server (could be on the same machine, but in a different Application Server, in other words, on a different port) you have to do some CORS Filters configurations.
The frontend code is running on a server - that means it's an application. Postman is a client, just like Google Chrome or any other browser. That's the explanation why you can do the request without any problem from Postman but unsuccessful from your frontend application.
I guess you enabled the Access-Control-Allow-Origin header on the backend
Now you have to allow your custom headers with Access-Control-Allow-Headers
Whenever I use fetch and I need to add headers to the request I do it this way:
headers: new Headers({
Accept: 'application/json',
Authorization: token,
'Content-Type': 'application/json',
}),
so you might want to try this approach, also in order to debug this issue you might want to check your Netowrk tab and verify which headers are sent with the request.
You need to add an Authorization bearer header.
For instance:
headers = new Headers({
'Authorization': `Bearer ${authorizationCodeOrCredentials}`
});
In your code:
return fetch(`{SERVICE API URL}`, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + someValue, // Add this line
'userName': "username",
'password': "password",
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
If you are using Linux system & If you have chrome in it...
Run your chrome using following command
/opt/google/chrome/chrome --disable-web-security --user-data-dir
Try now, If everything works fine then it's CORS issue from Backend.

Categories

Resources