![](/img/trans.png)
[英]Unhandled Rejection (SyntaxError): Unexpected end of JSON input with Get request fetch
[英]API Fetch Issue: Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected identifier “Server”
我在從我的 api 獲取時遇到問題,並且我不斷收到上述錯誤,並且不知道出了什么問題。 基本上我要做的是創建一個用戶,然后將令牌返回給我以創建另一個配置文件。
我不完全確定這是前端還是后端的問題,也不知道如何確定是其中之一。 這是前端的代碼:
let response;
await fetch('https://herokuapiurl.com/api/users', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
'name': name,
'email': email,
'password': password,
'phoneNumber': phoneNumber,
'userName': userName,
'address': address
})
})
.then(msg => {
response = msg.json()
return response
})
.then(msg => console.log(JSON.stringify(msg) + ' This is part of the .then()'))
fetch('https://apiurl.com/api/profiles', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'x-auth-token': response
},
body: JSON.stringify({
'name': name,
'email': email,
'password': password,
'phoneNumber': phoneNumber,
'userName': userName,
'address': address
})
}
)
.then(msg => msg.json())
.then(msgJSON => console.log(msgJSON + ' this fired'))
.catch((error) => console.log(error))
任何幫助將非常感激。 謝謝。
編輯
這是我們在 api 上的用於注冊用戶的路由:
router.post(
"/",
[
check("name", "name is required").not().isEmpty(),
check("email", "Please inclue a valid email").isEmail(),
check(
"password",
"Please enter a password with 6 or more characters"
).isLength({ min: 1 }),
check("phoneNumber", "Phone Number is required").isMobilePhone(),
check("address", "address is required").not().isEmpty(),
check("userName", "Username is required").not().isEmpty(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password, phoneNumber, userName, address } = req.body;
try {
let user = await User.findOne({ userName });
if (user) {
return res
.status(400)
.json({ errors: [{ msg: "User already exists" }] });
}
console.log(userName);
//get users gravitar
const avatar = gravatar.url(email, {
s: "200",
r: "pg",
d: "mm",
});
user = new User({
name,
email,
password,
phoneNumber,
userName,
address,
gravatar: avatar,
});
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get("jwtSecret"),
{ expiresIn: 360000 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
console.log(userName);
//res.send("User registered");
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
);
module.exports = router;
原來問題出在后端。 它需要唯一的電子郵件,並且來自過去注冊測試的現有電子郵件導致后端行為不可預測。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.