Getting an error for API request with javascript - javascript

I have an issue fetching the data from the local server. It was perfectly working and nothing changed. After some fetching, I started to receive an errors such as:
for POST request
Unexpected token '<', \"<!DOCTYPE \"... is not valid JSON
and for GET request
unexpected token 's', \"server lau\"... is not valid json
The server side of the application is created with node js and run in localhost port 5000. It is a very simple "get" and "post" express methods.
And the frontend fetching method as next:
fetch("http://localhost:5000", options)
.then(res => res.json())
.then(res => console.log(res))
.catch((err) => console.log(err.message))
and the options as:
const optionPost= {
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": {
"string": "omurzak"
}
}
const optionGet= {
"method": "GET",
"headers": {
"Content-Type": "application/json"
}
}
Hope you understand the issue.
Thank you!

Related

Gzip decompression post request, axios, Node.JS

I'm doing a post request using axios in node.js.
The response is gzip data (behind, it's a huge json)
My goal is to read the json file behind the res (gzip).
Currently, my request is:
await axios({
method: "post",
url: process.env.API_URL + "/collection",
headers: {
"Content-Type": "application/json",
"Accept-Encoding": "gzip, deflate, br",
},
data: {
project: req.body.project,
platform: req.body.platform,
},
decompress: true,
}).then(async (response) => {
console.log(response.data);
});
But I receive data like:
�1�����Q��:GR}��"-��}$K�ևҹ\��°<ܖqw�Vmp�������Y!�����܋a�F�]� ���K%}0�rЈ^�<��/�>
��Q���C7��R>�]§.,j�rg�6�MUVH��_Xq�����}|��a����$����K��cˠ��[�vv�����o�6�v�?~�����h���'Kn.��e��ZUW�;���ŗ��Ӹ׿6j%��M������Էʫ�c1��A�����.�t8�����Ș,����_��C�����۬���?q$޽#�CFq...
Does someone have any suggestion?
Thanks !
In my case, I want to get the information of my accessToken (from Google provider), then I can send a GET request like this:
const googleOauth2Url = `https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${accessToken}`;
const { data } = await axios.get(googleOauth2Url, {
responseType: "arraybuffer",
decompress: true,
});
Then I receive the data that looks similar to yours. I investigate and find out that the data is compressed with gzip, then to use it we must decompress the data.
Now I use zlib.
zlib.gunzip(data, function (error, result) {
console.log(result.toString());
return result.toString();
});
And the final result is:
{
"issued_to": "some data,
"audience": "some data",
"user_id": "some id",
"scope": "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
"expires_in": 2971,
"email": "sample#gmail.com",
"verified_email": true,
"access_type": "offline"
}

Fetch Post Request with Parameters is returning 400 status code?

I have a Post Request using fetch in react native, but I get a status code 400 for this, what is wrong with the code?
function sendRequest2() {
fetch(`https://sandbox-api.dexcom.com/v2/oauth2/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: JSON.stringify({
code: "value1",
client_id: "value2",
client_secret: "value3",
redirect_uri: "http://www.google.com",
grant_type: "authorization_code",
}),
})
.then((response) => {
response.json();
})
.then((data) => {
console.log(data);
})
.catch((err) => console.log("The error is: " + err));
}
Check your content-type, replace it by :
headers: {
"Content-Type": "application/json",
},
helpfull link : application/x-www-form-urlencoded or multipart/form-data?
You can try by removing JSON.stringify
That would solve the issue
Moreover you have shared a lot of open information regarding your server openly.
You must either hide it or add some dummy values. Sharing such a secure data openly is not recommended in open community.

Cant get data from express server

I am trying to send a GET request and receive a response on my client side (react).
On my express server:
app.get('/', function (req, res) {
res.send('Hey, I came from the express server');
})
When I use postman to sent the request I receive a good answer:
So I don't think the problem is with the server.
A problem:
When I try to send the request using react like this:
const getData = () => {
fetch("http://localhost:8081", {
method: "GET",
mode: 'no-cors'
}).then(response => console.log(response));
}
For some reason the response status is 0 and not 200 (I am receiving status code of 200 when checking this request with postman and also on the chrome network tab).
In addition, if I try to print response.body it will be null.
The response:
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
[[Prototype]]: Response
What am I doing wrong here?
You can add a proxy property to your package.json:
"proxy": "http://localhost:8081",
And then just use / as your fetch endpoint.
fetch('/'...
You need to transfer your response to an text or json like:
const getData = () => {
fetch("http://localhost:8081", {
method: "GET",
mode: 'no-cors'
}).then(response => response.json()).then(data => console.log(data))
}
Besides .json() there are even more methods. Its everything written down in the docs. You just need to google it:
https://developer.mozilla.org/en-US/docs/Web/API/Response#methods

Node/Express - res.status().send() only sends the status but does not send an object

I am having an issue with a route in my backend where res.status().send() will only send the client the status code, but it will not send the client the object located inside of send().
Here is my code (redacted all code but the problem for brevity):
exports.user_signup = (req, res) => {
const { body } = req;
const { companyName, password, email } = body;
User.find({ email: email }, (err, previousUsers) => {
if (err) {
return res.status(400).send({
message: "There was an issue signing up."
});
} else if (previousUsers.length > 0) {
return res.status(403).send({
message: "Records show this email is linked to another account."
});
}
}
When I make my fetch request from the client, the response only returns the status code from the server, but nowhere in the response is the object in the send() method on the server. Just spitballing, I threw res.status(200).json(object) at it to send the object as json to no avail.
Here is my `fetch request from the client:
fetch("http://localhost:3000/users/accounts/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
}).then(response => console.log(response));
}
To show what response I am getting, I purposely posted some form data from the client to the route that would throw the 403 error, and this is the response I get in the browser console:
Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 403, ok: false, …}
So I am able to successfully send the status back from the route to the client, however I can not for the life of me figure out why send() does not send the object along with it.
The body of the response that comes back from fetch() is a ReadableStream. You need to process it to turn it into something usable. Normally you would call response.json() to parse it as a JSON object:
fetch("http://localhost:3000/users/accounts/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(response => console.log(response));
}

JS Fetch takes only OPTIONS request and print that out

Im trying to make a request from my React App to my backend server, the frontend do a OPTIONS request and that is OK, the problem is that my then on the fetch console logs the OPTIONS response, and not the real response that is made efter the OPTIONS request.
fetch('http://localhost:8080/api/kp/ticket', {
headers: {
"token": sessionStorage.getItem('token')
},
mode: 'cors',
method: 'GET'
}).then(data => console.log(data));
try this
fetch('http://localhost:8080/api/kp/ticket', {
headers: {
"token": sessionStorage.getItem('token')
},
mode: 'cors',
method: 'GET'
}).then(data => (data.json())
.then(res => console.log(res));
Check in "Other" tab in chrome devtools. Not in XHR

Categories

Resources