fetch 访问 API 接口的基本用法参照:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
如果我们把 fetch 放在一个函数里, 可以这样写: 下面的代码也包含如何post form
async function fetchToken(setToken) {
let formData = new FormData();
formData.append("token", process.env.REACT_APP_AUTH_SECRET);
formData.append("next_url", window.location.pathname);
const response = await fetch(process.env.REACT_APP_AUTH_OBTAIN, {
method: "POST",
body: formData,
});
return response.json();
}
然后在别的函数里这样调用:
login = async () => {
const result = await fetchToken();
...
};