I cannot get the fetch api to work with the mailchimp api in React. I'm also using webpack to run a devserver.
This is what I have:
componentDidMount() {
let authenticationString = btoa('123:myapikey-us17');
authenticationString = "Basic " + authenticationString;
fetch('https://us17.api.mailchimp.com/3.0/lists/fakelistid/segments', {
mode: 'no-cors',
method: 'GET',
credentials: 'same-origin',
headers: new Headers({
'Authorization': authenticationString,
'Accept': 'application/json',
'Content-Type': 'application/json'
})
}).then(function(e){
console.log("fetch finished")
}).catch(function(e){
console.log("fetch error");
})
}
I've tested the exact same api request in Postman and that works fine.
When I try this in React I keep getting a 401 status code saying "Your request did not include an API key."
Related
I'm trying post request by my react app and I have return status 415. I tested this endpoint by postman exactly which I got from this console.log(JSON.stringify(data.data)); and all is right. I notice that my request haven't the same content-type which I set in fetch method.
fetch("http://localhost:8080/v1/useranswers", {
method: "POST",
mode: "no-cors",
headers: {
Accept: " */*",
"Content-Type": "application/json",
},
body: JSON.stringify(data.data),
}).then(function (response) {
return response;
});
I add line #CrossOrigin(origins = "*") in my controller and all is right :)
I made a server query via an app developed using react-native. I used fetch API and it turns out any query with authorization header not working. POST and GET method REQUESTS that don't expect Authorization headers at the server side works well. Some Queries at the server side are protected with authorization and when I make such queries including authorization header, I always get '401:unauthorized' error.
But such queries works well with POSTMAN. Any suggestions here would be of great help.
getThingsApi() {
let uri = "https://example.com/things/";
let req = {
method: "GET",
credentials: "include",
//mode: "no-cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
//'Access-Control-Request-Method': 'GET',
//'Access-Control-Request-Headers': 'origin, x-requested-with',
'Origin': '',
'Host':'example.com',
'authorization': 'Basic '+Base64.btoa('aaa:bbb'),
'Cache-Control': 'no-cache'
}
};
fetch(uri, req)
.then(response => response.json())
.then(responseJson => {
console.log("ResponseAxis::" + JSON.stringify(responseJson));
console.log("ResponseAxis::" + JSON.stringify(responseJson));
alert("ResponseAxis::" +JSON.stringify(responseJson));
})
.catch(error => {
console.log("Error::" + JSON.stringify(error));
});
}
Issue is fixed. We used Fetch API and fetch Api converts all headers into lower-case(eg: authorization) and the server side expects upper-case starting letter(eg: Authorization). After changing the server side code to be case-insensitive, everything works fine.
There are different ways to make a REST call in react-
e.g
axios.post('link', JSON.stringify(data1),
{
headers: {"content-type" : "application/json", "Access-Control-Allow-Origin" : "*"}})
.then(response => {
console.log("res:", response)
})
.catch(err =>{
console.log(err)
})
}
OR
fetch('http://localhost:8080/feedbacks/addfeedback', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
body:body
What is the most effiecient way to enable CORS.
Is there any other way that I can do this either in frontend or backend?
It depends on what HTTP library you are using.
See What is difference between Axios and Fetch?.
I usually use Axios, next what i do is creating a global instance and configuring Axios once.
export const api = axios.create({
baseURL: '_URL_',
timeout: 1000,
withCredentials: false,
responseType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // whatever you want
}
});
// You can add common headers later
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Also i'm enabling CORS on my server side application.
Thanks to #henrik123 for good explanation:
The browser is going to see that some Javascript request has tried to initiate a request to a different domain, subdomain or port than what the browsers is currently at. If any of these things are different, the CORS kicks in. Doesn't matter if you use Axios, Fetch or any other other library
I am using the standard cloud API for Jira and having troubles using their API to create an issue. I have tried both basic and token auth, both with the same CORS error.
I have followed the steps listed in these documents (here and here) and can get the API working in Postman, but not in my React code. I believe this has to do with Postman not sending the preflight options with the request.
Here is a sample of my request with basic auth:
fetch(`https://{DOMAIN}.atlassian.net/rest/api/3/issue/`, {
method: "POST",
credentials: 'include',
headers: {
"Content-Type": 'application/json',
"Accept": 'application/json',
"Authorization": "Basic {ENCODED USERNAME/PASSWORD}"
},
body: JSON.stringify(data)
})
.then(...)
Here is a sample of my request with token:
fetch(`https://{DOMAIN}.atlassian.net/rest/api/3/issue/`, {
method: "POST",
credentials: 'include',
headers: {
"Content-Type": 'application/json',
"Accept": 'application/json',
"Authorization": "bearer {TOKEN}"
},
body: JSON.stringify(data)
})
.then(...)
Does anyone know how to overcome this CORS error with Jira Cloud API? I found this article but would assume the issue has been resolved: https://jira.atlassian.com/browse/JRACLOUD-30371
UPDATE
Could not get this working via basic auth, however the newer OAuth 2.0 is working (only for GET requests).
Follow updates on this stack overflow question: JIRA Cloud REST API (OAuth 2.0) Error 403 on POST Requests
Can't send authorization header with rest API. Got 'OPTIONS' error with status 0. All headers and options are allowed on the server. Server is written on PHP.
Here is my request:
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData},{
headers:{ 'Content-Type':'multipart/form-data',
Authorization:`Bearer ${token}`}
})
It seems like it does not send the header when there is authorization. However, it works, if i delete authorization, and leave only content type
This should do the trick
axios({
method: 'POST',
url:`${API_URL}users/${23}/profile/main/update`,
headers: {
'Content-Type':'multipart/form-data',
'Authorization':`Bearer ${token}`},
data: formData
})
Refer docs for browser
Try to send as below:
var headers = {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData}, headers)
Try using Ajax call below:
import $ from 'jquery';
$.ajax({
url:`${API_URL}users/${23}/profile/main/update`,
processData: false,
contentType: false,
data : formData,
method : "POST",
headers: {
"Authorization": `Bearer ${token}`
}
});
I had this same issue, it is possible that you are not passing the sent auth header from your apache config to your php application.
you might need to set
WSGIPassAuthorization On
inside your virtualhost config.
Check this