首页 > 解决方案 > 我无法从服务器获取 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

标签: node.js

解决方案


你不能同时使用res.sendFileres.json

  • res.json()表示 HTTP 响应。
  • res.sendFile()在给定路径传输文件。

推荐阅读