【问题标题】:I can't fetch the json from server我无法从服务器获取 json
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 如何在视图渲染中使用从 post 请求中获得的 json?
  • 你设置所有模板都位于/views目录下yapp.set('views', __dirname + '/views');app.set('view engine', 'pug'); // 一些模板,如手把或哈巴狗 res.render("auth", {orders:your_json});
猜你喜欢
  • 2016-08-03
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 2020-05-31
  • 2013-07-27
  • 2016-07-04
相关资源
最近更新 更多