为您的 HTTP 客户端服务创建一个可重用的组件。
// httpService.js
import axios from "axios"
axios.interceptors.response.use(null, error => {
const expectedError =
error.response &&
error.response.status >= 400 &&
error.response.status < 500;
if (!expectedError) {
console.log("Logging the error", error);
alert("An unexpected error occurred");
}
return Promise.reject(error);
});
export default {
get: axios.get,
post: axios.post,
put: axios.put,
delete: axios.delete
};
以下是对用户信息的注册发布请求示例
// authService.js
import http from "../services/httpService"
import { apiUrl } from "../../config.json"
const apiEndPoint = apiUrl + "";
export function register(user) {
return http.post(apiEndPoint, {
firstname: user.firstname,
secondname: user.secondname,
email: user.email,
phone: user.phone,
password: user.password,
});
}
注意Config.json 文件包含您的 API URL。
下面是一个注册表单组件示例,它有一个 doSubmit 方法,用于在成功注册后调用服务器并导航到登录页面。
...
doSubmit = async () => {
// Call Server
try {
await userService.register(this.state.data);
this.props.history.push("/Login"); // Programmatic Routing
} catch (ex) {
if (ex.response && ex.response.status === 400) {
const errors = { ...this.state.errors };
errors.username = ex.response.data;
this.setState({ errors });
}
}
....
此示例仅用于说明目的,可以根据您的 API 请求进行相应修改。