【发布时间】:2022-12-29 21:28:23
【问题描述】:
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
我的后端在node.js 和express.js
import express from 'express';
import bcrypt from 'bcrypt-nodejs';
import cors from 'cors';
const app = express();
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(cors());
const database = { users: [
{
id: '123',
name: 'John',
email: 'john@gmail.com',
password: 'cookies',
entries: 0,
joined: new Date()
},
{
id: '124',
name: 'Tom',
email: 'Tom@gmail.com',
password: 'apple',
entries: 0,
joined: new Date()
}
}
app.get('/', (req, res) =>{
res.send(database.users)
})
app.listen(3002, () => {
console.log('app is running on port 3002');
})
我的前端在React.js
这是一个大项目,所以我只会展示导致错误的部分,即 response.json() 部分。当您摆脱 json() 时,一切都很好,但为了让我从后端接收数据,我需要执行 .json(),这会给出该错误。让我知道是否需要其他信息
componentDidMount(){
fetch('http://localhost:3000')
.then(response => response.json())
.then(console.log)
}
【问题讨论】:
-
您正在获取错误的端口。您的服务器侦听 3002 端口,因此在获取时将其 url 更改为“localhost:3002”。在您的获取请求中使用“res.json()”而不是“res.send”,这将返回带有正确标头的响应。详情可以check this。