[英]Why am I getting an error of Unexpected token < in JSON at position 0
I am creating a MERN app, I am new to this.我正在创建一个 MERN 应用程序,我是新手。 I tried following some tutorials on the net but I have encountered some error.我尝试在网上学习一些教程,但遇到了一些错误。
I am submitting the post request like this.我正在提交这样的帖子请求。 As you can see I am not specifying the content type because I know that if you are using the 'multipart/form-data it will automatically append it to the headers.正如您所看到的,我没有指定内容类型,因为我知道如果您使用的是“multipart/form-data”,它会自动将其附加到标题中。 I am using a react hook here which is why I am not directly using the fetch method.我在这里使用了一个 react 钩子,这就是为什么我没有直接使用 fetch 方法。
const formData = new FormData();
formData.append("email", formState.inputs.email.value);
formData.append("name", formState.inputs.name.value);
formData.append("password", formState.inputs.password.value);
formData.append("image", formState.inputs.image.value);
const responseData = await sendRequest(
`${process.env.REACT_APP_BACKEND_BASE_URL}/api/users/signup`,
"POST",
formData
);
meanwhile my signup route is like this, UNDER user-routes.js同时我的注册路线是这样的,在user-routes.js 下
router.post(
"/signup",
fileUpload.single("image"),
[
check("name").not().isEmpty(),
check("email")
.normalizeEmail() // Test@test.com => test@test.com
.isEmail(),
check("password").isLength({ min: 6 }),
],
usersController.signup
);
as you can also see, I am catching it in the route by using the fileUpload.single("image")
如您所见,我通过使用fileUpload.single("image")
在路由中捕获它
if you need to see my hook that I am using here it is, but I am pretty sure that the hook works fine.如果你需要看看我在这里使用的钩子,它是,但我很确定钩子工作正常。 and it has no issues whatsoever, so here it is: this is a react hook它没有任何问题,所以这里是:这是一个反应钩子
export const useHttpClient = () => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState();
const activeHttpRequests = useRef([]);
const sendRequest = useCallback(
async (url, method = "GET", body = null, headers = {}) => {
setIsLoading(true);
const httpAbortCtrl = new AbortController();
activeHttpRequests.current.push(httpAbortCtrl);
try {
const response = await fetch(url, {
method,
body,
headers,
signal: httpAbortCtrl.signal,
});
const responseData = await response.json();
// console.log("Response: ", response);
// console.log("Data: ", responseData);
activeHttpRequests.current = activeHttpRequests.current.filter(
(reqCtrl) => reqCtrl !== httpAbortCtrl
);
if (!response.ok) {
throw new Error(responseData.message);
}
setIsLoading(false);
return responseData;
} catch (err) {
setError(err.message);
setIsLoading(false);
throw err;
}
},
[]
);
const clearError = () => {
setError(null);
};
useEffect(() => {
return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
activeHttpRequests.current.forEach((abortCtrl) => abortCtrl.abort());
};
}, []);
return { isLoading, error, sendRequest, clearError };
};
I will include the signup here from my users.controller :我将从我的users.controller包括在这里注册:
const signup = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError("Invalid inputs passed, please check your data.", 422)
);
}
const { name, email, password } = req.body;
let existingUser;
try {
existingUser = await User.findOne({ email: email });
} catch (err) {
const error = new HttpError(
"Signing up failed, please try again later.",
500
);
return next(error);
}
if (existingUser) {
const error = new HttpError(
"User exists already, please login instead.",
422
);
return next(error);
}
let hashedPassword;
try {
hashedPassword = await bcrypt.hash(password, 12);
} catch (err) {
const error = new HttpError(
"Could not create user, please try again.",
500
);
return next(error);
}
//res.json({ message: "AFTER HASHING" });
const createdUser = new User({
name,
email,
image: req.file.path,
password: hashedPassword,
places: [],
});
try {
await createdUser.save();
} catch (err) {
const error = new HttpError(
"Signing up failed, please try again later.",
500
);
return next(error);
}
let token;
try {
token = jwt.sign(
{ userId: createdUser.id, email: createdUser.email },
process.env.JWT_KEY,
{ expiresIn: "1h" }
);
} catch (err) {
const error = new HttpError(
"Signing up failed, please try again later.",
500
);
return next(error);
}
res
.status(201)
.json({ userId: createdUser.id, email: createdUser.email, token: token });
};
You may want to use JSON.Parse()
around your responseData你可能想在你的 responseData 周围使用JSON.Parse()
When ever I run into this bug it is because I either,每当我遇到这个错误时,都是因为我,
This link goes into more depth about the bug and common ways of dissecting the issue.此 链接更深入地了解错误和剖析问题的常用方法。
Try console.log() in your hook before you send the data and also log what the responseData looks like after it retrieves the data在发送数据之前在钩子中尝试 console.log() 并在它检索数据后记录 responseData 的样子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.