我有一个在 Next.js 中创建的注册表单,我正在将带有数据的请求发送到 http://localhost:8888/api/user/register。新用户已成功创建,但是我收到 XHR 错误,我不知道出了什么问题。
这是我的服务器代码。 /register 路线
route.post("/register", async (req: Request, res: Response, next: NextFunction) => {
interface RegisterData{
username: string,
firstName: string,
lastName: string,
email: string,
password: string
}
const newUserData: RegisterData = req.body;
if(newUserData == null || Object.keys(newUserData).length == 0){
return res.status(503).send({ error: "ERROR: User data not sent, try again !" });
}
const firstName = newUserData.firstName;
const lastName = newUserData.lastName;
const username = newUserData.username;
const email = newUserData.email;
const password = newUserData.password;
if(firstName == null || lastName == null || username == null || email == null || password == null ){
return res.status(400).send({ error: "ERROR: User data not complete, try again !" });
}
const foundUser = await USER.findOne({
$or: [
{ 'username': username },
{ 'email' : email }
]
}).catch((err: any) => {
console.log(err);
return res.status(400).send({ error: "ERROR: Something went wrong, try again !" });
})
if (foundUser){
if(email == foundUser.email){
return res.status(400).send({ error: "ERROR: Email already in use !" });
}else{
return res.status(400).send({ error: "ERROR: Username already in use !" });
}
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new USER({
firstName: firstName,
lastName: lastName,
username: username,
email: email,
password: hashedPassword
})
try {
await newUser.save();
return res.status(200).send({ message: "New user created !" });
} catch (err) {
console.log(err);
return res.status(400).send({ error: "ERROR: Something went wrong, try again !" });
}
});
这是我在 app.tsx 文件中的 CORS 修复:
app.use((req: Request, res: Response, next: NextFunction) => {
//CORS FIX
//ADD HEADER TO REQUREESTS
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE');
next();
});
app.use(bodyParser.json())
app.use("/api/user/", UserController); //ROUTES FOR USER
//*** 404 ***//
app.all('*', (req: Request, res: Response, next: NextFunction) => {
res.status(404).send("Page not found: Unknown URI");
})
这是我在前端的 FetchAPI。
const onSubmit = async (event: any) => {
interface Payload{
username: String | undefined,
firstName: String | undefined,
lastName: String | undefined,
email: String | undefined,
password: String | undefined,
}
event.preventDefault();
if(username == null || firstName == null || lastName == null || email == null || password == null || passwordRepeated == null){
setErrorMessage("ERROR: Make sure all fields are populated")
setShowErrorMessage(true);
return;
}
if(password != passwordRepeated){
setErrorMessage("ERROR: Passwords don't match !")
setShowErrorMessage(true);
return;
}
const payload: Payload = {
username,
firstName,
lastName,
email,
password
}
const body = JSON.stringify(payload);
console.log(body);
const response = await fetch("http://localhost:8888/api/user/register", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: body,
});
const data = await response.json();
if (response.ok) {
console.log(data.message)
}else{
setErrorMessage(data.error);
}
}