I've been working on this for months now and have talked with my host, the company etc and I can make my api call work on their developer page which has example code to test their API but for the life of me I cannot get it to work on my Wordpress site and it is very much needed.
My initial code is as follows:
const options = {
method: 'POST',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: 'Basic XXXXXXXREDACTEDXXXXX'
},
body: JSON.stringify({firstName: 'John', lastName: 'Doe', phoneNumber: '5444455555'})
};
fetch('https://a.eztexting.com/v1/contacts', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
The first error I receive is:
Access to fetch at 'https://a.eztexting.com/v1/contacts' from origin 'https://businessofimagination.com' 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.
after trying many different headers all over Wordpress and my theme I finally included:
"mode: 'no-cors'," into my code
updated code is as follows:
const options = {
method: 'POST',
mode: 'no-cors',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: 'Basic XXXXXXREDACTEDXXXXXX'
},
body: JSON.stringify({firstName: 'John', lastName: 'Doe', phoneNumber: '5444455555'})
};
fetch('https://a.eztexting.com/v1/contacts', options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err));
Now the errors I receive are:
POST https://a.eztexting.com/v1/contacts 403 (403 forbidden)
and
SyntaxError: Unexpected end of input
I don't understand why it refuses to work, or what in Wordpress is preventing this. Please any help would be incredible. This has been an incredibly frustrating journey for something that in theory should work fairly seamlessly.
Related
I was working on a React APP which fetches data from https://restcountries.com/v2/all and now I have an error.
useEffect(() => {
fetch(`https://restcountries.com/v2/all`)
.then((r) => r.json())
.then((data) => {
if (data !== undefined) {
setCountries(data);
} else {
alert('Can´t Load Data');
}
});
}, []);
**
use this format with header
** ##
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {`enter code here`
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
}, []);
You are getting a CORS error which means target domain of api (restcountries) does not allow other domains to fetch data.
The solution to this problem is a server side browser or headless browser. Like selenium and puppeteer
https://www.selenium.dev/
https://github.com/puppeteer
But i have tested and api is giving me data in browser with same fetch code. I cant reproduce the problem. Its an issue with something else
this is happening due to multiple reason like due to authentication or your are not sending token in request header second due to server down or may be your are passing wrong param to request third one my be this endpoint can me access by only specific domains url.
This may be a newbiew question (I haven't used the fetch api before), but I can't figure out what wrong with my request.
fetch('https://securetoken.googleapis.com/v1/token?key=' + API_KEY, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'grant_type=refresh_token&refresh_token=' + refreshToken
})
.then(response => console.log(response))
.catch(error => console.error(error))
I'm trying to exchange a refresh token for an id token following the guidelines here, but for some reason I'm getting a Bad Request response...
Response { type: "cors", url: "https://securetoken.googleapis.com/v1/token?key=[API_KEY]", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
My key is correct, and the refreshToken is also straight from a response from a service on Firebase SDK.
Where exactly is my mistake?
UPDATE
Showing the context where fetch is executed in a Next.js app:
I'm running this code in dev (localhost) using Firebase Emulators.
I managed to find additional error logs that state { code: 400, message: "INVALID_REFRESH_TOKEN", status: "INVALID_ARGUMENT" }.
So, this indeed seems to be an issue with the refresh_token. Can it be because it has been emitted by Firebase Emulators?
useEffect(() => {
return firebase.auth().onIdTokenChanged(async user => {
if (user) {
fetch('https://securetoken.googleapis.com/v1/token?key=' + process.env.NEXT_PUBLIC_FIREBASE_API_KEY, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'grant_type=refresh_token&refresh_token=' + user.refreshToken
})
.then(response => console.log(response))
.catch(error => console.error(error))
}
})
}, [])
In the end the cause for the issue was the fact that the refreshToken issued when using Firebase Emulators is not valid when exchanging for an idToken.
Quite an edge case, but perhaps someone may find this helpful.
I have a rest api endpoint and I am checking it using POSTMAN which is posting correctly. But, when I am doing it using JAVASCRIPT FETCH, I am not able to post it. Below is my code for fetch:
const { inputAOI, wktForCreation } = this.state
fetch('http://192.168.1.127:8080/aoi/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userName: 'fuseim', aoiName: inputAOI, wkt: wktForCreation }),
mode: 'no-cors'
}).then(function (response) {
if (response.ok) {
return response.json()
} else {
throw new Error('Could not reach the API: ' + response.statusText)
}
}).then(function (data) {
console.log({ data })
}).catch(function (error) {
console.log({ error })
})
Below is the image for the request headers.
It is seen in the above image that in Request Headers, the Content-Type is still text/plain but I am sending application/json as shown in above fetch code.
Check the response preview in console.
Below is correct POSTMAN request:
As hinted in the comments, the problem is with the mode:"no-cors"
Content-Type is considered a simple header, and should be allowed without cors, but only with the following values:
application/x-www-form-urlencoded
multipart/form-data
text/plain
See: https://fetch.spec.whatwg.org/#simple-header
If you are running the API on the same host/port as the script, you should use mode: "same-origin" alternatively add the host/port that the script is running on as an allowed origin on the API.
For more information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Instead of
headers: {
'Content-Type': 'application/json'
}
you could try:
headers: new Headers({
'Content-Type': 'application/json'
})
in my React app, I have the following API POST to allow the user to edit their profile (name and image).
static updateProfile(formData, user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken()
}),
mode: 'no-cors',
method: "POST",
body: formData
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
The problem with the above is the header with the Authorization token is not being sent in the POST...
How can I get the Authorization header to be send in the fetch request above?
FYI, for non-multipart forms, the authorization token is sent successfully like so:
static loadProfile(user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken(),
'Accept' : 'application/json',
'Content-Type' : 'application/json',
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
You can’t use no-cors mode if you set any special request headers, because one of effect of using it for a request is that it tells browsers to not allow your frontend JavaScript code to set any request headers other than CORS-safelisted request-headers. See the spec requirements:
To append a name/value pair to a Headers object (headers), run these steps:
Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return.
In that algorithm, return equates to “return without adding that header to the Headers object”.
Authorization isn’t a CORS-safelisted request-header, so your browser won’t allow you to set if you use no-cors mode for a request. Same for Content-Type: application/json.
If the reason you’re trying to use no-cors mode is to avoid some other problem that occurs if you don’t use, the solution is to fix the underlying cause of that other problem. Because no matter what problem you might be trying to solve, no-cors mode isn’t going to turn out to be a solution in the end. It’s just going to create different problems like what you’re hitting now.
By using below code you can make a fetch request with Authorization or bearer
var url = "https://yourUrl";
var bearer = 'Bearer '+ bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone',
'Content-Type': 'application/json'}
}).then((responseJson) => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));
I am posting the details of user in api ,using the access token in header which i got in sign up but getting this error --> Unexpected end of JSON input. My code is
postNameToApi()
{
console.log("inside post api");
fetch('https://MyPostApi', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer'+'Qwjubq41KAWw9uI2NMj4TPQ9t24PxC'
},
body: JSON.stringify({
dob:'1992-04-18',
gender: 'femanino',
is_professional:true,
is_referee:false
})
}).then((response) => response.json())
.then((responseData) => {
console.log("inside responsejson");
console.log('response:',responseData);
//this.setState({response:responseData});
}).done();
}
This is because your response is not in json format. Space is missing between Bearer and your token, i think this will solve your issue.
'Authorization':'Bearer '+'Qwjubq41KAWw9uI2NMj4TPQ9t24PxC'
Try your api call with postman first.