When I post a request in a local host this code runs fine but in production, this shows me an error – VM49:1 Uncaught (in promise) SyntaxError: Unexpected token ‘I’, "Internal S"… is not valid JSON
Hosting :
Frontend – Netlify and Backend -Render
This is my frontend code:
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch(`${BASE_URL}/api/auth/createuser`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
"name": credentials.name,
"email": credentials.email,
"password": credentials.password,
}),
});
const json = await response.json();
console.log(json);
if (json.success) {
// Save the auth token and redirect
navigate("/");
props.showAlert("Account Created Successfully", "success");
} else {
props.showAlert("Invalid Details", "danger");
}
};
and my backend code is
const express = require("express");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const { body, validationResult } = require("express-validator");
const fetchuser = require('../middleware/fetchUser');
const JWT_SECRET = "marufisagoodb$oy";
// ROUTE 1: Create a User using: POST "/api/auth/signup". No login required
router.post(
"/createuser",
[
body("name", "Enter a valid name").isLength({ min: 3 }),
body("email", "Enter a valid email").isEmail(),
body("password", "Password must be atleast 5 characters").isLength({
min: 5,
}),
],
async (req, res) => {
let success = false;
// If there are errors, return Bad request and the errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({success, errors: errors.array() });
}
// Check whether the user with this email exists already
try {
let user = await User.findOne({ email: req.body.email });
if (user) {
return res
.status(400)
.json({
success,
error: "Sorry a user with this email already exists",
});
}
//Hashing a password using bcryptjs
const salt = await bcrypt.genSalt(10);
const securepass = await bcrypt.hash(req.body.password, salt);
// Create a new user
user = await User.create({
name: req.body.name,
password: securepass,
email: req.body.email,
});
//JWT
const data = {
user: {
id: user.id,
},
};
const authtoken = jwt.sign(data, JWT_SECRET);
// res.json(user)
success = true
res.json({ success, authtoken });
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
}
);
// ROUTE 2: Authenticate a User using: POST "/api/auth/login". No login required
router.post(
"/login",
[
body("email", "Enter a valid email").isEmail(),
body("password", "Password cannot be blank").exists(),
],
async (req, res) => {
let success = false;
// If there are errors, return Bad request and the errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { email, password } = req.body;
try {
let user = await User.findOne({ email });
if (!user) {
success = false;
return res
.status(400)
.json({ error: "Please try to login with correct credentials" });
}
const passwordCompare = await bcrypt.compare(password, user.password);
if (!passwordCompare) {
success = false;
return res.status(400).json({
success,
error: "Please try to login with correct credentials",
});
}
const data = {
user: {
id: user.id,
},
};
const authtoken = jwt.sign(data, JWT_SECRET);
success = true;
res.json({ success, authtoken });
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
}
);
// ROUTE 3: Get loggedin User Details using: POST "/api/auth/getuser". Login required
router.post("/getuser", fetchuser, async (req, res) => {
try {
userId = req.user.id;
const user = await User.findById(userId).select("-password");
res.send(user);
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
});
module.exports = router;
Please solve this error
2
Answers
Update your JSON response this way in the backend:
Don’t forget to set success to false, while sending JSON response.
Let me know, if it’s not works!!
Make sure that your
NODE_VERSION
of your local environment and deployment environment are the same.While making a fetch request, please make a request object and then pass it as an argument in the fetch function.
Also, always use a catch after fetch and return null or anything fitting with your architecture. You cannot always expect a response and the code will crash in case there is no response as you are accessing
.json()
method.