Unexpected token '<', "<!DOCTYPE "... is not valid JSON"/>
caught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
使用 node.js 和 express.js 连接前端和后端并使用 vite
时出现此错误这是我的 server.js 代码
`/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
const mongoose = require('mongoose')
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const userRouters = require('./routes/user.js')
const port = 8080
const app = express()
app.use(express.urlencoded({extended: true}));
app.use(cors({
credentials: true,
}))
app.use(express.json())
app.use(bodyParser.json())
//routes
app.use('/',userRouters)
//schema
const UserSchema = require('./models/userSchema.js')
app.post('/login',(req,res)=>{
res.send("This is the login page")
})
app.post('/signup',(req,res)=>{
res.send("This is the signup page")
})
const DB = "mongodb+srv://fk28:[email protected]/test"
mongoose.connect(DB , {
useNewUrlParser:true,
useUnifiedTopology:true
}).then(()=>{
console.log("connection successful")
}).catch((err)=>{
console.log(err)
})
app.listen(port , ()=>{
console.log("listening to port",port)
})`
这是前端的**package.json **
`{
"name": "podiverse",
"private": true,
"version": "0.0.0",
"type": "module",
"proxy": "http://localhost:8080",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint src --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"antd": "^5.4.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.10.0"
},
"devDependencies": {
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"@vitejs/plugin-react-swc": "^3.0.0",
"autoprefixer": "^10.4.14",
"eslint": "^8.38.0",
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.3.4",
"postcss": "^8.4.23",
"tailwindcss": "^3.3.1",
"vite": "^4.3.1"
}
}
`
这是register.jsx代码
`/* eslint-disable no-undef */
/* eslint-disable react-hooks/rules-of-hooks */
import {
Row,
Col,
Space,
Typography,
Button,
Checkbox,
Form,
Input,
// Select,
// Option,
} from "antd";
import { LockOutlined, UserOutlined, MailOutlined } from "@ant-design/icons";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
const register = () => {
const navigate = useNavigate()
const [register , setRegister] = useState({
username:"", email:"" , password:"" , confirmpassword:""
})
let name , value;
const handlechange = (e)=>{
name = e.target.name
value = e.target.value
setRegister({...register , [name]:value})
}
const onRegister = async (e)=>{
e.preventDefault()
const {username, email , password , confirmpassword} = register
const res = await fetch('/signup' ,
{
withCredentials: true,
credentials: 'include',
}, {
method:"POST",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
username, email , password , confirmpassword
})
})
const data = res.json()
console.log(res)
if(data.status === 422 || !data){
window.alert("Registration unseccessful")
console.log("Registration unseccessful")
}else{
window.alert("Registration successful")
console.log("Registration successful")
navigate('/login')
}
}
return (
<div className="h-screen bg-fixed bg-center bg-no-repeat bg-cover bg-hero">
<Row>
<Col
span={0}
lg={{
span: 10,
offset: 1,
}}
>
<div className="flex flex-col items-center justify-center w-full h-auto mx-16 my-16 bg-fixed bg-center bg-no-repeat bg-cover border rounded-md bg-bgImg py-52 border-gray-50 ">
<Typography.Title
className=" font-heading"
style={{ color: "white", fontSize: "40px" }}
>
PODIVERSE
</Typography.Title>
<Typography.Paragraph
className="font-heading"
style={{ color: "white", fontSize: "20px" }}
>
Listen in and discover a world of <br />
knowledge and entertainment
</Typography.Paragraph>
</div>
</Col>
<Col span={24} lg={{ span: 12, offset: 1 }}>
<Row className="lg:mt-24 lg:ml-10 xs:mt-10">
<Col
span={20}
offset={2}
md={{ span: 12, offset: 6 }}
lg={{ span: 12, offset: 6 }}
className="max-w-xs text-center"
>
<div className="mb-8 ">
<Space align="center">
<Typography.Title level={2} style={{ color: "white" }}>
SignUp
</Typography.Title>
</Space>
<Typography.Title level={5} style={{ color: "white" }}>
{"Register now, to get started"}
</Typography.Title>
</div>
<Form
name="normal_login"
className=" login-form"
initialValues={{ remember: true }}
>
<Form.Item
name="username"
rules={[
{ required: true, message: "Please input your Username!" },
]}
>
<Input
prefix={<UserOutlined className="site-form-item-icon" />}
placeholder="Username"
type="text"
name="username"
onChange={handlechange}
value={register.name}
/>
</Form.Item>
<Form.Item
name="email"
rules={[
{
type: "email",
message: "The input is not valid E-mail!",
},
{
required: true,
message: "Please input your E-mail!",
},
]}
>
<Input prefix={<MailOutlined />}
placeholder="E-mail"
type="text"
name="email"
onChange={handlechange}
value={register.email}
/>
</Form.Item>
<Form.Item
name="password"
rules={[
{ required: true, message: "Please input your Password!" },
]}
>
<Input.Password
prefix={<LockOutlined className="site-form-item-icon" />}
type="password"
placeholder="Password"
name="password"
onChange={handlechange}
value={register.password}
/>
</Form.Item>
<Form.Item
name="confirm"
dependencies={["password"]}
rules={[
{
required: true,
message: "Please confirm your password!",
},
({ getFieldValue }) => ({
validator(_, value) {
if (!value || getFieldValue("password") === value) {
return Promise.resolve();
}
return Promise.reject(
new Error(
"The two passwords that you entered do not match!"
)
);
},
}),
]}
>
<Input.Password
prefix={<LockOutlined className="site-form-item-icon" />}
type="password"
placeholder="Confirm Password"
name="confirmpassword"
onChange={handlechange}
value={register.confirmpassword}
/>
</Form.Item>
<Form.Item className="flex ">
<Form.Item name="remember" valuePropName="checked" noStyle>
<Checkbox style={{ color: "white" }}>Remember me</Checkbox>
</Form.Item>
<a
className="ml-[88px] login-form-forgot"
href=""
style={{ color: "white" }}
>
Forgot password
</a>
</Form.Item>
<Form.Item>
<Button
onClick={onRegister}
type="primary"
block
className="mb-5 text-black bg-white"
>
Submit
</Button>
<span style={{ color: "white" }}>Or</span>
<br />
<a href="" className="mt-3 text-blue-500 underline ">
Already have a account, login to continue !
</a>
</Form.Item>
</Form>
</Col>
</Row>
</Col>
</Row>
</div>
);
};
export default register;
`
我试图通过添加 await 来解决这个错误
const data = res.json()
但是还是不行。看起来是 JSON 问题 谁能帮我解决这个问题?
回答如下:更多推荐
caught (in promise) SyntaxError: Unexpected token '<', "<!DOCT
发布评论