React app can't get data from ExpressJS API - reactjs

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.

Related

Fetch POST request console.log not working correctly

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.

Is it possible to use API Routes as Proxy to my existing RoR Backend

Every time NextJs request for an api, it will come first to api routes before it redirected to my RoR backend service.
I use this to encrypt my access token to session NextJS using iron-session once I get the data from backend.
## src/pages/api/login.ts
const loginRoute = async (req: NextApiRequest, res: NextApiResponse) => {
const response = await fetch(`backend-service/authorizations.json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: req.body.username,
password: req.body.password
})
})
.then((res) => {
if (!res.ok) {
return res.text().then((text) => {
throw new Error(text)
})
}
return res
})
.then((res) => res.json())
.catch((err) => {
res.status(401).json({ message: err })
})
if (response) {
req.session.user = response
await req.session.save()
res.json(response)
}
}
export default withSessionRoute(loginRoute)
Is this a valid use case for API Routes in NextJS?
Thanks in advance!

Frontend and backend url not matching

I have a problem with matching routes. I am runnning react app on port localhost:3000, and node/express server is running on port localhost:3001.
I am trying to create a club by firing this request on the frontend:
async addClub(club) {
try {
let postData = await fetch(`${this.backendUrl}/club`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({...club}),
});
this.backendUrl is correctly imported
Route on the backend file is:
router.post('/club', async (req, res) => {
try {
const body = req.body;
await new Club(body).save((err, club) => {
if (err) return console.log(err)
console.log('New club created');
res.status(200).send({ msg: 'Club created' });
});
} catch(err) {
res.status(400).json({
msg: 'Bad Request'
})
}
})
But for some reason frontend execution cannot find route specified on the backend.
I get an error: POST http://localhost:3001/club 404 (Not Found)
I have other routes through which I create other things and they work perfectly.

On Postman when ı send get request to my backend Api ı can get a response but in my app ı only get 401 unauthorizated

I have a api and i am using passport.js.When user logged in i give them JWT and set axios default header to token.
axios.defaults.headers.common["Authorization"] = token;
Everything work when i send request on Postman.But doesn't work on my React App.(except my default test route)
router.get("/test", (req, res) => res.json({ msg: "User works" }));
I added cors to my express app.It did not work.
this is my backend route
router.get(
"/getuserclass",
passport.authenticate("jwt", { session: false }),
(req, res) => {
User.findOne({ _id: req.user.id })
.populate("classes", { _id: 1, name: 1 })
.then(user => res.json(user))
.catch(() => {
return res.status(403).json({ msg: "Not found" });
});
}
);
and this is my get request
axios
.get("/api/users/getuserclass", {
withCredentials: true,
crossdomain: true
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error.response);
});
on React app it gave this error
401 unauthorized

Fetch request always returns network error

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.

Resources