这是一个健全的实现注册功能?


  1. async和await在正确的位置给出这个箭头函数
  2. 开头的const呢?可以吗?
  3. 功能的流程及其划分。(我把它放在一个不同的文件,并在提交一个表单在我的注册组件,它将被调用)
  4. 我应该保存这个函数的结果在一个变量在我的注册组件,然后评估它,看看下一步该做什么?

有用的信息:在提交表单之前,我正在与Yup进行表单验证。所以从服务器返回的都是"邮件已收"或"注册成功"。

谢谢!

/* 
File: src/utils/authentication.js
Author: jreyes
Date: 01-26-2021
*/
/** Register new user */
const signupAuth = async () => {
await fetch('http://localhost:8080/signup', {
method: 'POST',
mode: 'cors',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password,
firstname,
lastname
})
})
.then(response => {
if (!response.ok) {
throw new Error('Please check your network.');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
export { signupAuth };

你应该试着这样做:

export const signupAuth = (email, password, firstname, lastname) => {
return fetch('http://localhost:8080/signup', {
method: 'POST',
mode: 'cors',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password,
firstname,
lastname
})
})
};

和后面:

import { signupAuth } from "./file";
signupAuth(email, password, firstname, lastname)
.then(response => {
})
.catch(error => {

});
// or this way
try {
const response = await signupAuth(email, password, firstname, lastname);
// do you stuff here
} catch (error) {
// handle error here
}

最新更新