This question already has answers here:
Trying to use fetch and pass in mode: no-cors
(9 answers)
Closed 19 days ago.
I was making a site for a personal project when I ran into an error.
The client requests for the list of directories and the server returns a JSON file back to the client but the client brings up the error 'syntaxerror: unexpected end of input'. I checked the server output and it says it sent the file successfully, and when I accessed the server through the web manually, I got a valid JSON output (I checked it online). Is this a problem with the client?
server code:
app.get('/votes', (req, res) => {
fs.readFile(path.resolve(__dirname, 'testing.json'), (err, data) => {
if (err) {
res.status(500).send('Error reading file');
} else {
res.status(200).json(JSON.parse(data));
}
});
});
client code:
async function dataFetch() {
await fetch('https://serverIP/votes', {
method: 'GET',
mode: "no-cors",
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(`${data} <-- data`);
jsonFile = data;
})
.catch(error => {
alert("an error has occured: "+error)
console.log(`Error: ${error}`);
}
I tried using other methods of fetching, but none were successful.
i think you missed the } at the end.
await fetch('https://serverIP/votes', {
method: 'GET',
mode: "no-cors",
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(`${data} <-- data`);
jsonFile = data;
})
.catch(error => {
alert("an error has occured: "+error)
console.log(`Error: ${error}`);
})}```
I am building a user website, where the admin should be able to delete users.
My project is build using Azure SQL database.
I have in my controllers file, come up with an endpoint deleteUser
deleteUser
const deleteUser = (req, res) => {
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
const { id } = req.query
request.query(
`DELETE FROM users where User_ID = '${id}'`,
function (err, recordset) {
if (err) {
console.log(err);
} else if (!id) {
res.json("Please provide an ID")
} else {
res.json(`User with ID: ${id} has been deleted!`)
}
}
);
});
};
I am then trying to make a call to this endpoint using fetch and EJS.
My code in EJS script tag
<script>
document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {
e.preventDefault();
fetch('http://localhost:3000/deleteUser', {
method:'DELETE',
headers: {
"Content-Type": "application/json",
},
body: null
})
.then((response) => console.log(response))
.catch((e) => {
console.log(e)
})
})
</script>
I console log the response, so the route must be good, but it seems as it doesn't parse the ID into the fetch. What is the right way to approach this?
Thanks in advance!
Solution
I have come up with follow solution - which is not the best, but works.
document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {
e.preventDefault();
// delete user using fetch
const id = document.getElementById('userId').textContent
fetch(`http://localhost:3000/deleteUser?id=${id}`, {
method:'DELETE',
headers: {
"Content-Type": "application/json",
},
body: null
})
.then((response) => console.log(response))
.catch((e) => {
console.log(e)
})
})
Thanks for the contribution!
Should the id not be in the URL of the fetch request? You are asking for the id from the request params, so it should probably be appended to the path like
const id = wherever your id comes from;
fetch('http://localhost:3000/deleteUser?id=${id}...'
You'll need to get the user's id in your button method as well, but would need more of your code to see where that comes from.
Usually using an ID for deletion is best approach
fetch('http://localhost:3000/deleteUser/:id...'
However, you can pass id in anyway in body, params, query or even headers)
I have this route set up on my server with nodejs/express:
const testSync = (req, res) => {
//bookingLink and requestOptions defined here
fetch(bookingLink , requestOptions)
.then(response => response.text())
.then(result => {
res.sendStatus(200)
})
.catch(error => {
console.log('error', error)
res.sendStatus(404)
});
}
router.post('/test-sync', testSync);
And here is my client side call :
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({url: `${bookingLink}`})
}
fetch(`${protocol}//${domainName}/api/test-sync`, requestOptions)
.then(response => response.text())
.then(result => {
setSyncTest("success")
})
.catch(error => {
setSyncTest("fail")
});
The point of the client side call is to change the state of syncTest hook to "fail" if the link provided to the endpoint is bad. Now, if the link is bad it shows me the 404 error code in the console, but the syncTest doesn't change. I think it doesn't throw the error. How should I do to throw the error in order to change the hook state ?
Update your function to:
const testSync = (req, res) => {
//bookingLink and requestOptions defined here
return fetch(bookingLink , requestOptions)
.then(response => response.text())
.then(result => {
res.sendStatus(200)
})
.catch(error => {
console.log('error', error)
res.sendStatus(404)
});
}
router.post('/test-sync', testSync);
You need to return your fetch request, which is a Promise. What is happening now is that your function is returning right away before fetch is complete.
or more direct/cleaner layout:
const testSync = (req, res) => fetch(bookingLink , requestOptions)
.then(response => response.text())
.then(result => res.sendStatus(200))
.catch(error => {
console.log('error', error)
res.sendStatus(404)
});
router.post('/test-sync', testSync);
Client
Your client code is not handling the 404 correctly. Based on the instructions at MDN an HTTP 404 or even a 500 will not reject the promise. You will need to handle them in the then().
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
I am coding this in react.js and I really have no idea what is going on. I am using unirest to make the api call but the fetch isn't working so to me it seems I am doing something wrong in the fetch statement.
unirest.get("https://heisenbug-la-liga-live-scores-v1.p.mashape.com/api/laliga/table")
.header("X-Mashape-Key", "Lzrv6ktkq3mshGiQJrPDa9cBxcDGp1Vcdncjsn1DweG4jU5ref")
.header("Accept", "application/json")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
fetch(unirest)
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json)
this.setState({
record: json.records[0]
});
})
I am working on Reactjs redux on front-end and Rails API as a back-end.
So now I call API with Fetch API method but the problem is I cannot get readable error message like what I got inside the network tabs
this is my function
export function create_user(user,userInfoParams={}) {
return function (dispatch) {
dispatch(update_user(user));
return fetch(deafaultUrl + '/v1/users/',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(userInfoParams)
})
.then(function(response) {
console.log(response);
console.log(response.body);
console.log(response.message);
console.log(response.errors);
console.log(response.json());
dispatch(update_errors(response));
if (response.status >= 400) {
throw new Error("Bad response from server");
}
})
.then(function(json){
console.log("succeed json re");
// We can dispatch many times!
// Here, we update the app state with the results of the API call.
dispatch(update_user(json));
});
}
}
But when errors came I cannot figure out how to get readable response message like I got when I check on my browser network tabs
So this is what I got from the network tabs when I got errors.
My console
This is my rails code
def create
user = User.new(user_params)
if user.save
#UserMailer.account_activation(user).deliver_now
render json: user, status: 201
else
render json: { errors: user.errors }, status: 422
end
end
But I cannot find out how can I get that inside my function
Since the text is hidden inside promise within response object, it needs to be handled like a promise to see it.
fetch(bla)
.then(res => {
if(!res.ok) {
return res.text().then(text => { throw new Error(text) })
}
else {
return res.json();
}
})
.catch(err => {
console.log('caught it!',err);
});
Similar to your answer, but with a bit more explanation... I first check if the response is ok, and then generate the error from the response.text() only for the cases that we have a successful response. Thus, network errors (which are not ok) would still generate their own error without being converted to text. Then those errors are caught in the downstream catch.
Here is my solution - I pulled the core fetch function into a wrapper function:
const fetchJSON = (...args) => {
return fetch(...args)
.then(res => {
if(res.ok) {
return res.json()
}
return res.text().then(text => {throw new Error(text)})
})
}
Then when I use it, I define how to handle my response and errors as needed at that time:
fetchJSON(url, options)
.then((json) => {
// do things with the response, like setting state:
this.setState({ something: json })
})
.catch(error => {
// do things with the error, like logging them:
console.error(error)
})
even though this is a bit old question I'm going to chime in.
In the comments above there was this answer:
const fetchJSON = (...args) => {
return fetch(...args)
.then(res => {
if(res.ok) {
return res.json()
}
return res.text().then(text => {throw new Error(text)})
})
}
Sure, you can use it, but there is one important thing to bare in mind. If you return json from the rest api looking as {error: 'Something went wrong'}, the code return res.text().then(text => {throw new Error(text)}) displayed above will certainly work, but the res.text() actually returns the string. Yeah, you guessed it! Not only will the string contain the value but also the key merged together! This leaves you with nothing but to separate it somehow. Yuck!
Therefore, I propose a different solution.
fetch(`backend.com/login`, {
method: 'POST',
body: JSON.stringify({ email, password })
})
.then(response => {
if (response.ok) return response.json();
return response.json().then(response => {throw new Error(response.error)})
})
.then(response => { ...someAdditional code })
.catch(error => reject(error.message))
So let's break the code, the first then in particular.
.then(response => {
if (response.ok) return response.json();
return response.json().then(response => {throw new Error(response.error)})
})
If the response is okay (i.e. the server returns 2xx response), it returns another promise response.json() which is processed subsequently in the next then block.
Otherwise, I will AGAIN invoke response.json() method, but will also provide it with its own then block of code. There I will throw a new error. In this case, the response in the brackets throw new Error(response.error) is a standard javascript object and therefore I'll take the error from it.
As you can see, there is also the catch block of code at the very end, where you process the newly thrown error. (error.message <-- the error is an object consisting of many fields such as name or message. I am not using name in this particular instance. You are bound to have this knowledge anyway)
Tadaaa! Hope it helps!
I've been looking around this problem and has come across this post so thought that my answer would benefit someone in the future.
Have a lovely day!
Marek
If you came to this question while trying to find the issue because response.json() throws "Unexpected token at position..." and you can't find the issue with the JSON, then you can try this, basically getting the text and then parsing it
fetch(URL)
.then(async (response) => {
if (!response.ok) {
const text = await response.text()
throw new Error(text)
}
// Here first we convert the body to text
const text = await response.text()
// You can add a console.log(text), to see the response
// Return the JSON
return JSON.parse(text)
})
.catch((error) => console.log('Error:', error))
.then((response) => console.log(response))
I think you need to do something like this
export function create_user(user,userInfoParams={}) {
return function (dispatch) {
dispatch(update_user(user));
return fetch(deafaultUrl + '/v1/users/',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(userInfoParams)
})
.then(function(response) {
console.log(response);
console.log(response.body);
console.log(response.message);
console.log(response.errors);
console.log(response.json());
return response.json();
})
.then(function(object){
if (object.errors) {
dispatch(update_errors(response));
throw new Error(object.errors);
} else {
console.log("succeed json re");
dispatch(update_user(json));
}
})
.catch(function(error){
this.setState({ error })
})
}
}
You can access the error message with this way:
return fetch(deafaultUrl + '/v1/users/',
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(userInfoParams)
})
.then(function(response) {
console.log(response);
console.log(response.body);
console.log(response.message);
console.log(response.errors);
console.log(response.json());
dispatch(update_errors(response));
if (response.status >= 400) {
throw new Error("Bad response from server");
}
})
.then(function(json){
console.log("succeed json re");
// We can dispatch many times!
// Here, we update the app state with the results of the API call.
dispatch(update_user(json));
})
// here's the way to access the error message
.catch(function(error) {
console.log(error.response.data.message)
})
;
The best choice is not to catch the error in the fetch because this will be useless:
Just in your api put a response with not code error
static GetInvoicesAllData = async (req,res) =>
{
try{
let pool = await new Connection().GetConnection()
let invoiceRepository = new InvoiceRepository(pool);
let result = await invoiceRepository.GetInvoicesAllData();
res.json(result.recordset);
}catch(error){
res.send(error);
}
}
Then you just catch the error like this to show the message in front end.
fetch(process.env.REACT_APP_NodeAPI+'/Invoices/AllData')
.then(respuesta=>respuesta.json())
.then((datosRespuesta)=>{
if(datosRespuesta.originalError== undefined)
{
this.setState({datosCargados:true, facturas:datosRespuesta})
}
else{ alert("Error: " + datosRespuesta.originalError.info.message ) }
})
With this you will get what you want.
You variables coming back are not in response.body or response.message.
You need to check for the errors attribute on the response object.
if(response.errors) {
console.error(response.errors)
}
Check here https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
You should actually be returning an error response code from the server and use the .catch() function of the fetch API
First you need to call json method on your response.
An example:
fetch(`${API_URL}`, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(userInfoParams)
})
.then((response) => response.json())
.then((response) => console.log(response))
.catch((err) => {
console.log("error", err)
});
Let me know the console log if it didn't work for you.