node.js - 我无法从服务器获取 json
问题描述
控制器
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'))
})
注册.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>
在我进行发布请求后,它会在位置 0 处抛出“未捕获(承诺中)语法错误”:JSON 中的意外令牌 <。
我尝试了所有这些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
解决方案
你不能同时使用res.sendFile
和res.json
。
res.json()
表示 HTTP 响应。res.sendFile()
在给定路径传输文件。
推荐阅读
- ruby-on-rails - Google::Cloud::Bigquery:Module in rails 的未定义新方法
- excel - 使用合并的单元格将范围复制到范围中
- asp.net-core - 如何使用剃刀视图 ASP .Net Core 从 JWT 声明角色
- groovy - 如何正确格式化我的 URl 以使用图形 APi 过滤器
- python - 检查图像的 RGB 值是否满足没有循环的条件
- html - 如何避免 CSS 网格拉伸行?
- javascript - 如何避免重复相同的功能并使其在 Javascript 中通用
- sql - 在 FROM 语句中使用查询参数
- linux - 文件未在存储和公用文件夹之间同步
- java - 使用名为 Wait 的变量声明特征会导致覆盖编译器错误