How to make HTTP request to HereUS? - javascript

I'm getting the follower feed of an user via HereUS API. It will be the main page of my application. Application is a client for HereUS.
I am not able to make HTTP request with React. URL, method, headers and data is how it must be; controlled with copy-paste to Python 3 script and it worked.
Code:
fetch('https://hereus.pythonanywhere.com/API/FEED_FOLLOWS', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'username#domain',
password: 'password'
})
})
.then(res => {
return res.json()
})
.then(data => console.log(data))
.catch(error => console.log(error));
Error:
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Response content:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<title>400 Bad Request</title>\n<h1>Bad Request</h1>\n<p>The browser (or proxy) sent a request that this server could not understand.</p>\n
I expected:
{data: [{community: '', date_created: 'Sat, 25 Jun 2022 12:20:18 GMT', email: 'islekcaganmert#barsposta.com', id: 1, text: '"Ne Mutlu Türküm Diyene" -Mustafa Kemal ATATÜRK', username: 'Çağan Mert İŞLEK'}]}

Related

Response not expected after sending a post request using Content-Type "application/javascript" on fetch API is sent

When I send the following request from my Chrome devtools
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: {
title: 'foo',
body: 'bar',
userId: 1,
},
headers: {
'Content-type': 'application/javascript',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
This is the output I get:
{id: 101}
Which is not what I expect, in fact I expect
{title: 'foo', body: 'bar', userId: 1, id: 101}
that I get when I use Content-Type of 'aplication/json' like in the code below:
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
So if you follow the documentation for the service you are using and POST some JSON and say it is JSON then the server-side code processes it as you expect.
… but if you disobey the documentation and post an object which the browser converts to the string [object Object] and (incorrectly) claim it is JavaScript then the server fails to process it.
This is normal behaviour and firmly in the "don't do that" category.
Aside: Allowing clients to post JavaScript programs which the server would (presumably) have to execute to do anything useful with would be extremely dangerous. This is a whole category of security problems which developers try to avoid, not encourage.

Integrating API with Wordpress

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.

Bad Request when fetching id token from Google

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.

VM1661:1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0

Hi guys there have been an error in my site for quite long and I have searched whole internet for the answers but didn't found any solutions here is my onsubmit code
onSubmit = () => {
fetch("http://localhost:2000/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then((response) => response.json())
.then(console.log(this.state.signinEmail, this.state.signinPassword))
.then((data) => console.log(data));
};
Also i have checked the response of the network tab it says success but getting this error don't know how to get rid of it. I have also checked the solution of the
Stackoverflow that write Accept:application/json but still didn't worked,but it gives me "bad request" error
The backend code is:
app.post("/signin", (req, res) => {
if (
req.body.email === database.users[0].email &&
req.body.password === database.users[0].password
) {
res.send("success");
} else {
res.status(400).json("error logging in");
}
});
I have also tested it through Postman it works successfully on it with no errors.
This the json server.
This happens when you make a request to the server and parse the response as JSON, but it’s not JSON.
fetch('/url').then(res => res.json())
The actual request worked fine. It got a response. But the res.json() is what failed.
The root cause is that the server returned HTML or some other non-JSON string.
You can try changing res.json() to res.text().
onSubmit = () => {
fetch("http://localhost:2000/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then((response) => response.text())
.then((data) => console.log(data));
};

Unexpected end of JSON input error in Post request on api using access token in react-native

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.

Categories