[英]SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data?
[英]error from register: TypeError: res is undefined/ SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
如何擺脫這兩個控制台錯誤?
我正在使用 react/mern 創建一個市場應用程序。 我當前的問題是,每當我嘗試注冊或登錄用戶時,我都會不斷收到這兩個錯誤“來自寄存器的錯誤:TypeError: res is undefined/ SyntaxError: JSON.parse: unexpected character at line 1 column 1 JSON 數據”。
我已經嘗試了一切,查看了存在的每個 stackoverflow 問題,但沒有任何效果。 當我在開發工具中查看網絡控制台響應時,它說注冊/登錄已成功,但沒有任何內容進入我的數據庫,並且我不斷收到這兩個控制台錯誤。
Register.js (錯誤具體引用了handleSubmitReg函數)
import { useState } from 'react';
import { Form, Button, Spinner, Alert, Card } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { registerUser } from '../functions/userData';
import '../components/register.scss';
import React from 'react'
function Register() {
const [loading, setLoading] = useState(false);
const [alertShow, setAlertShow] = useState(false);
const [error, setError] = useState(null);
const[userData, setUserData] = useState({
name: null,
email: "",
university: "",
password: "",
repeatPassword: ""
});
const handleChanges = (e) => {
e.preventDefault();
setUserData({ ...userData, [e.target.name]: e.target.value});
}
const handleSubmitRegistration= (e) => {
e.preventDefault();
setLoading(true);
registerUser(userData)
.then(res => {
if (!res.error) {
window.location.replace('/auth/login')
} else {
setLoading(false);
setError(res.error);
setAlertShow(true);
}
}).catch(err => console.error('error from register: ', err))
}
return (
<>
<div className="register">
<Card>
<Card.Body>
<h1 className="auth-heading">Sign Up!</h1>
<Form className="col-lg-8" onSubmit={handleSubmitRegistration}>
{alertShow &&
<Alert variant="danger" onClose={() => setAlertShow(false)} dismissible>
<p>
{error}
</p>
</Alert>
}
<Form.Group controlId="forName" className="col-lg-8">
<Form.Label>Name *</Form.Label>
<Form.Control type="text" name="name" placeholder="Student123 or Stud Student" onChange={handleChanges} required />
<Form.Text muted>
The name can be your real one or a username.
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicEmail" className="col-lg-12">
<Form.Label>Email address *</Form.Label>
<Form.Control type="email" name="email" placeholder="student@gmail.com" onChange={handleChanges} required />
</Form.Group>
<Form.Group controlId="forUniversity" className="col-lg-12">
<Form.Label>University/Institution *</Form.Label>
<Form.Control type="text" name="university" placeholder="Monash University" onChange={handleChanges} required />
</Form.Group>
<Form.Group controlId="formBasicPassword" className="col-lg-6">
<Form.Label>Password *</Form.Label>
<Form.Control type="password" name="password" placeholder="Password" onChange={handleChanges} required />
<Form.Text muted>
Your password must be 8-20 characters long
</Form.Text>
</Form.Group>
<Form.Group className="col-lg-6">
<Form.Label>Repeat Password *</Form.Label>
<Form.Control type="password" name="repeatPassword" placeholder="Repeat password" onChange={handleChanges} required />
</Form.Group>
{loading ?
<Button className="col-lg-12 btnAuth" variant="dark" disabled >
Please wait... <Spinner animation="border" />
</Button>
:
<Button variant="dark" className="col-lg-12 btnAuth" value="Add to DB" type="submit">Sign Up</Button>
}
<p className="bottom-msg-paragraph">Already have an account? <Link to="/auth/login">Sign In</Link>!</p>
</Form>
</Card.Body>
</Card>
</div>
</>
)
}
export default Register;
用戶數據.js
const baseUrl = 'http://localhost:5000';
export async function registerUser(userData) {
return (await fetch(`${baseUrl}/auth/register`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({userData})
})
.then((response) => response.json())
.then((userData) => {
console.log('Success:', userData);
})
.catch((error) => {
console.log('Error:', error);
}
))
}
export async function loginUser(userData) {
return (await fetch(`/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify(userData)
})).json();
}
您的registerUser
function 不返回任何值,只返回console.log
。 所以像這樣修復它
export async function registerUser(userData) {
return (await fetch(`${baseUrl}/auth/register`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({
userData
})
})
.then((response) => response.json()) // *** Returns Results
.catch((error) => error)) // *** Returns Error
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.