While I can post data to my server, and the server console.log works, I cannot for the life figure out why the client side console.log isn't working. What am I missing here?
The Error: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Status: 200 OK
Request: {"hotSauceId":32,"presentation":5,"viscosityId":3,"spiciness":10,"Flavor_Notes":["Constituent Peppers"],"overall_rating":5,"lovedit":true,"taster_notes":"test"}
Looks json to me?
Submit Handler:
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://jyh:3000', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"hotSauceId": sauce,
"presentation": presentation,
"viscosityId": viscosity,
"spiciness": spiciness,
"Flavor_Notes": flavor,
"overall_rating": overall,
"lovedit": loved,
"taster_notes": notes
}),
}).then(res => {
return res.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
};
Server Code:
app.post('/', async (req, res) => {
await Jyh.create({ // .create is a Sequelize method
hotSauceId: req.body.hotSauceId,
presentation: req.body.presentation,
viscosityId: req.body.viscosityId,
spiciness: req.body.spiciness,
Flavor_Notes: req.body.Flavor_Notes,
overall_rating: req.body.overall_rating,
lovedit: req.body.lovedit,
taster_notes: req.body.taster_notes
}).then(() => {
console.log('req.body: ', req.body);
}).catch((err) => {
console.log(err);
});
});
It should console.log the response in the client console, but instead I receive an error.
Github repository for the client and server app.
Related
I am first fetching xml data from an external api in my backend and then trying to send that to the frontend.
Backend (server):
app.get("/api", (req, res) => {
var request = require('request');
var options = {
'method': 'GET',
'url': 'http://link',
'headers': {
}
};
request(options, function (error, response) {
console.log("TEST1")
console.log(response.body)
if (error){
console.log("TEST2")
res.status(404).write("NO LUCK");
}
console.log("TEST3")
res.status(200).write(response.body);
});
});
The xml appears in my terminal correctly. TEST1 and TEST2 do too.
Frontend (client):
import XMLParser from 'react-xml-parser';
useEffect(() => {
fetch("/api")
.then(res => res.text())
.then(data => {
var xml = new XMLParser().parseFromString(data);
console.log(xml)
})
.catch(err => console.log(err));
}, []);
Nothing appears on the console. I got the frontend code from this stack overflow post.
fetch("/api")
.then((res) => res.body)
.then((data) => console.log(data));
If I log the response body like this I get a ReadableStream object. This is the only functionality I've been implementing so far so nothing should be interfering with it. When I try different approaches I keep needing to restart React or it will load endlessly when I refresh.
When I open http://localhost:3001/api I can see the xml data I'm trying to transfer.
Still not sure why it didn't work before but it works with this.
Frontend (client):
import axios from "axios";
axios.get('/api')
.then(xml => {
console.log(xml.data);
})
Backend (server):
app.get('/api', (req, res) => {
var axios = require('axios');
var config = {
method: 'get',
url: 'http://link',
headers: {'Content-Type': 'application/xml'}
};
axios(config)
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
console.log(error);
})
})
Hi I've been in a limbo with the problem. I'm trying to use the update method to update the iterations of clicks in my URL shortener project. The iterations update in the DB but then it isn't reflecting on the front end. I was thinking it would update in the then() function after fetching but then it seems like it didn't go in the then() function. My question is that is there something wrong with the code or is there an alternative way for it to get to the then()?
Client side (React)
const id = record._id;
fetch(`http://localhost:3001/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
.then((res) => { <-- Not executing :(
console.log("Update");
// function to refresh the page
handleRefresh();
})
.catch((err) => {
console.log(err);
});
Server side (Mongoose)
urlControllerRouter.post("/update/:id", (req, res) => {
const id = req.params.id;
UrlModel.findById(id)
.then((updateURL) => {
updateURL.click = req.body.click;
updateURL
.save()
.then(() => {
console.log(`[UPDATE] ${updateURL}`);
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
});
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
});
});
Your server isnt making a response after getting the request from the client so the connection is pretty much in limbo for lack of a better word.
You need to send a response to client
urlControllerRouter.post("/update/:id", (req, res) => {
const id = req.params.id;
UrlModel.findById(id)
.then((updateURL) => {
updateURL.click = req.body.click;
updateURL
.save()
.then(() => {
console.log(`[UPDATE] ${updateURL}`);
res.status(200).json({
message: updateURL
})
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
res.status(500).json({
message: err.message
})
});
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
res.status(200).json({
message: err.message
})
});
});
Btw, with fetch you need to add two thens to get the data you want.
But in your case you don't want to get the data so one would do
So something like this
fetch(`http://localhost:3001/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
.then(response => response.json())
.then((res) => { <-- Not executing :(
console.log("Update");
// function to refresh the page
handleRefresh();
})
.catch((err) => {
console.log(err);
});
Also you should actually add the backend link as a proxy value to your package.json as a better way of making the API call to the backend.
"name": "",
"version": "",
"main": "",
"proxy": "http://localhost:3001", //note the proxy
"license": "",
....
Then you just need to do this with fetch
fetch(`/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
I am having some trouble in getting fetch return data from my cloud function, I am only trying to write data into google spreadsheet with cloud function for now. Below is my current code so far.
I have a button with onClick={this.AddRecord} which will then call the cloud function
AddRecord = async () => {
await fetch(url, {
method: 'POST',
body: JSON.stringify({
date: this.getDate(),
name: this.state.name,
number: '\'' + this.state.number
})
})
.then((response) => {return response.json()})
.then((data) => {
alert(data) // this never gets executed
this.setState({message:data})
})
.catch((err) => {
this.setState({message: err})
});
}
and this is my cloud function POST handler:
case 'POST':
/* parse the string body into a usable JS object */
const data = JSON.parse(event.body);
const addedRow = await sheet.addRow(data);
return {
statusCode : 200,
body: JSON.stringify({
message : 'Posted successfully.',
rowNumber: addedRow._rowNumber - 1 // minus the header row
})
};
Appreciate it if anyone could point me in the right direction, as I have spent a lot of time trying to debug this but with no avail.
some of the resource that I have read so far:
fetch() call not returning any data
https://www.smashingmagazine.com/2020/06/rest-api-react-fetch-axios/
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Edit:
I have tried to call the cloud function via POSTMAN and successfully gotten a status 200 response with message.
So I can safely assume that the issue is not with the cloud function but the fetch function, but I am still clueless on which part of the code went wrong as they seem pretty much the same as other code example that I see online. I will only get TypeError: Failed to fetch when I switch back to POST from my react app.
Change your function to this:
AddRecord = async () => {
await fetch(url, {
method: 'POST',
headers: { 'Content-Type':'application/json' }, // here is the change
body: JSON.stringify({
date: this.getDate(),
name: this.state.name,
number: '\'' + this.state.number
})
})
.then((response) => response.json())
.then((data) => {
alert(data)
this.setState({message:data})
})
.catch((err) => {
this.setState({message: err})
});
}
I've run into issue where I can't get confirmation that user is authenticated from ExpressJS backend. I am using PassportJS with Google OAuth2.
When I try to access my API endpoint through browser, it returns the data I need. Why is this so? Is there a problem with cors and backend or with my request?
This is the error I get after a while on the same page: GET http://localhost:5000/api/auth/login/success net::ERR_EMPTY_RESPONSE
Here is my request:
useEffect(() => {
const fetchData = async () => {
await axios
.get(`${API_URL}/auth/login/success`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
},
})
.then((response) => {
if (response === 200) {
console.log(response);
console.log("200");
return response.json();
}
throw new Error("Failed to authenticate the user.");
})
.then((responseJson) => {
userHasAuthenticated(true);
setUser(responseJson.user);
console.log("responseJson");
setLoading(false);
})
.catch((error) => console.log(error));
};
fetchData();
}, [loading]);
I dont't get any outputs to the console.
Here is my route on the backend:
router.get("/login/success", (req, res) => {
console.log(req.user);
console.log("/login/success");
if (req.user) {
res.json({
success: true,
message: "User has successfully authenticated.",
user: req.user,
cookies: req.cookies,
});
}
});
When I try to access this route on my browser, I see the response and it prints it out in the console. But when I visit the frontend page from where the request is sent, nodejs console prints out undefined.
I almost finished creating React Native application, few days ago register action has stopped working.. I'm sending fetch request and it always returns network error altough there is 400 response and message that user exists, it stops there..
I'm destructuring the response and displays api response message instead of fetch network error but now it doesn't work. I'm doing the same for the login action and it works.
Could it be something with multipart/form-data ?
export const register = data => dispatch => {
dispatch(createUser());
const d = new FormData();
d.append("name", data.name);
d.append("email", data.email);
d.append("password", data.password);
d.append("avatar", data.avatar);
fetch(API_URL + "/register", {
method: "POST",
headers: {
"content-type": "multipart/form-data"
},
body:d
})
.then(response => response.json().then(user => ({ user, response })))
.then(({ user, response }) => {
if (!response.ok) {
console.log(response, user)
} else {
console.log(response, user)
}
})
.catch(err => {
throw err;
});
};
The api route works in Postman..
In this case, your using fetch which is Promise based incorrectly,
Try,
fetch(API_URL + "/register", {
method: "POST",
headers: { "content-type": "multipart/form-data" },
body:d
})
.then(response => {
console.log(response, response.json().user)
})
.catch(err => {
console.log(err)
});
Check the logs and see if it shows proper network response and debug from there.