【发布时间】:2021-09-08 20:54:42
【问题描述】:
控制器
const User = require('../Models/User')
const errHandler = require('express-async-handler')
const path = require('path')
const registerUser = errHandler(async (req, res) => {
const { name, nickName, email, password, role, perk } = req.body;
const user = await User.create({
name,
nickName,
password,
email,
role,
perk
})
res.status(201)
.sendFile(path.resolve('./Views/register.html'))
})
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Test</h1>
<script>
fetchUserData();
function fetchUserData() {
const fetchUser = fetch('http://localhost:5000/auth/register', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err))
}
</script>
</body>
</html>
在我进行发布请求后,它会抛出“Uncaught (in promise) SyntaxError”: Unexpected token
我尝试了所有这些React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 解决方案,但没有奏效。
然后我尝试将我的 json 包含在控制器中,例如:
res.status(201)
.json({
success: true,
data: user
})
.sendFile(path.resolve('./Views/register.html'))
但这一次它无法定义 JSON。
我最初的问题的图片:
路由
Router.post('/register', registerUser)
Router.use('/auth', auth) // this is index.js router
app.use('/', Router); // server router
所以我的路由是到 http://localhost:5000/auth/register
【问题讨论】:
-
当您尝试将响应解析为 json 时,它看起来像是在 html 中
-
我现在能做什么?
-
既然您收到了
404,您的问题很可能是路由问题,您能否显示路由代码 -
我已经展示过了。
标签: node.js