Keep getting error with `Fetch` `response.json()` - javascript

I have a JavaScript widget with the code:
function submit(email, pass){
fetch('http://127.0.0.1:8888/api/example', {
headers: {
"Content-Type": "application/json",
"Access-Control-Origin": "*",
"X-Requested-With": "XMLHttpRequest",
},
method: 'post',
body: JSON.stringify({
email: email,
password: pass
})
})
.then(
response => response.json(),///<---always give error
error => console.log('An error occurred.', error)
)
.then(
res => dispatch(completeTransactionsSave(res)
)
})
}
I keep getting error:
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
The line response.json() causes the error. I checked many tutorials and all seems to be using the same code and get back the result.
How can I resolve this?
Important Note
I just found out that happened because I am testing it with localhost. The moment I deploy it to real server, everything works fine.
The lesson, never test cross origin stuff with localhost.

Related

Vercel app gets caught in promise but localhost:4000 renders the fetch perfectly

In the localhost:4000, the fetch works perfectly and a user is able to register
Here's the code:
const response = await fetch("/api/users/signup", {
method: "POST",
body: JSON.stringify(user),
headers: {
"Content-Type": "application/json",
},
});
const json = await response.json();
if (!response.ok) {
setError(json.error);
}
But when the app is deployed to Vercel:
I received an error stating "Uncaught (in promise) SyntaxError: Unexpected end of JSON input".
Any thoughts?
I tried changing the fetch code and it did not work.

Unexpected end of JSON input error from DELETE method fetch

Here is the network screenshot
I am constantly getting the "Unexpected end of JSON input" error in console when I run this code, but it works (the item is deleted when I refresh page, but it doesn't rerender on it's own even tho the state is chenged and throws this error when I run it)
I checked if the problem is the type of id that I send when I call the function, and there is nothing wrong with it
const deleteScreen = (id:any) =>{
console.log(id)
fetch(`http://localhost:5002/admin/example?exampleId=${id}`, {
method: 'DELETE',
headers: {
'Content-type': 'application/json',
'Authorization' : `Bearer ${token.token}`
},
})
.then((response) => response.json())
.then((data) => {
console.log(data.result)
setAllScreens(data.result)
})
.catch((err) => {
console.log(err.message)
})
}
It's look like there is something wrong with your then block. Try with just console response instead response.json(). Or you can check with network tab response all well.

VM101:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I am using Sandbox for payment testing. Everything works fine till payment and the console throws an error:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
The error points to:
fetch(url, {
. I am not sure what's wrong with the Django app. I even have initialized URL at the top:
var url = "{% url 'payments' %}"
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
console.log(details);
sendData();
function sendData(){
fetch(url, {
method : "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
orderID: orderID,
transID: details.id,
payment_method: payment_method,
status: details.status,
}),
})
.then((response) => response.json())
.then((data) => {
window.location.href = redirect_url + '?order_number='+data.order_number+'&payment_id='+data.transID;
})
}
});
}
Either there is an internal server error, or you the server is not sending a Json response. You can check the status by using .then((response)=>console.log(response.status) to check if there is an internal server error, if the console.log shows 500 error code, then it is server error. else the server is not sending proper json response.
You are probably not returning json from the server, try doing res.text() instead of res.json(), and see if that fixes it, if it does, you are not returning proper json from your server.

React Native issue : [Unhandled promise rejection: TypeError: f is not a function. (In 'f()', 'f' is undefined)]

I am trying to make a login system using states and fetch so that the user can receive his valid token and then put it in storage with Async Storage.
I am still in the phase of communication with the API (expressjs). Everything works for the moment when I enter the email and the password I do receive the token in json but I have a warning type error which tells me:
[Unhandled promise rejection: TypeError: f is not a function. (In 'f()', 'f' is undefined)]
My code is very simple for the moment (I have absolutely no idea where it comes from):
const onSubmit = () => {
setLoading(true)
fetch('http://192.168.1.36:3000/api/users/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password
})
})
.then((response) => response.json())
.then((res) => console.log(res))
.catch((err) => console.log(err))
.finally(setLoading(false));
}
I don't know if the syntax I use with fetch is "good" and "optimize" for a login system, but I hope I was clear enough in my explanation.
Tanks
I think this has to do with your finally clause:
.finally(setLoading(false));
The finally function must be passed a function itself. Two ways to do this:
.finally(() => setLoading(false));
.finally(setLoading.bind(undefined, false));

JSON Parse error: Unrecognized token '<' parse - React Native

"JSON Parse error: Unrecognized token'<'"
Error is showing while hitting the API. (Response is in the JSON format.) I'm trying to build a login form but I cannot retrieve user data from my database server.
constructor(){
super()
this.state={
email:'',
password:'',
}
}
handleLoginUser(){
fetch('https://"mygoogleclouddatabaseip"/users/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state)})
.then(response => {
console.log(response);
return response.json();})
.then(responseData => {
console.log(responseData);
let result = JSON.parse(responseData);
return result;})
.then(data => {
if (result.success){
alert("Login successful");
}
else
alert("Unable to Login");
})
}
}
The problem is that your response isn't a valid json and it gives you the error when trying to do response.json().
Please debug it and to handle the case where response isn't a valid json.
Or the other problem can be here
let result = JSON.parse(responseData);
If responseData is already a javascript object, using JSON.parse will give you an error and if response.json() worked, it means that JSON.parse isn't necessary and is giving you the error.
You might ask
Why JSON.parse isn't necessary?
Because response.json() transforms the response to a javascript object and JSON.parse also do that.
The correct way is to use response.json() and not JSON.parse (only if the response is a valid json).

Categories