有人可以帮我将这些 axios 请求转换为 fetch 请求吗?我在 axios 中传输令牌时遇到问题。我认为它可以在 fetch 中工作,但我在重写请求时遇到问题。
import React, { useState, useEffect,useContext } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import axios from 'axios';
import AuthContext from '../context/AuthContext';
function FileUpload({ setUploads = () => {} }) {
const navigate = useNavigate();
const { id } = useParams();
const [photo, setphoto] = useState(null);
const { authTokens, logoutUser } = useContext(AuthContext);
const accesstoken = String(authTokens.access);
useEffect(() => {
if (id) {
axios.get(`http://xxxxxxx:8000/api/upload/${id}/`
).then((response) => {
setphoto(response.data.photo.name);
});
}
}, [id]);
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('photo', photo);
try {
let response;
if (id) {
response = await axios.patch(`http://xxxxxxx:8000/api/upload/${id}/`, formData);
setUploads((prevUploads) =>
prevUploads.map((upload) => (upload.id === response.data.id ? response.data : upload))
);
alert(`file updated successfully!`, navigate(`/upload/${response.data.id}`));
} else {
response = await axios.post('http://xxxxxx:8000/api/upload/', formData);
setUploads((prevUploads) => [response.data, ...prevUploads]);
alert('Upload created successfully!', navigate('/'));
}
setphoto(null);
} catch (error) {
console.error(error);
}
};
return (
<div className="container mx-auto px-4">
<form onSubmit={handleSubmit}>
<div className="mb-4">
<label htmlFor="photo" className="block font-medium text-gray-700">
photo/file
</label>
<input
type="file"
name="photo"
id="photo"
onChange={(e) => setphoto(e.target.files[0])}
className="border border-gray-400 rounded w-full px-3 py-2 mt-1 text-gray-900"
/>
</div>
<div className="mt-6">
<button
type="submit"
className="bg-blue-500 text-white font-medium py-2 px-4 rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-600 focus:ring-offset-2"
>
{id ? 'Update Upload' : 'Create Upload'}
</button>
</div>
</form>
</div>
);
}
export default FileUpload;
我尝试使用 axios 拦截器来表示令牌系统。 我尝试在每个请求中包含令牌
`'Authorization':'Bearer ' + String(authTokens.access).`
我有一个用 fetch 编写的请求,它适用于
`'Authorization':'Bearer ' + String(authTokens.access).`
下面是如何将给定的 Axios 请求转换为 JavaScript 中的
fetch
请求。请注意,对于带有 fetch 的 GET 和 PATCH/POST 请求,我们添加了 'Authorization': 'Bearer ' + accesstoken
标头以进行基于令牌的身份验证。
import React, { useState, useEffect, useContext } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import AuthContext from '../context/AuthContext';
function FileUpload({ setUploads = () => {} }) {
const navigate = useNavigate();
const { id } = useParams();
const [photo, setPhoto] = useState(null);
const { authTokens, logoutUser } = useContext(AuthContext);
const accesstoken = authTokens.access;
// Convert axios.get to fetch
useEffect(() => {
if (id) {
fetch(`http://xxxxxxx:8000/api/upload/${id}/`, {
headers: {
'Authorization': 'Bearer ' + String(accesstoken),
}
})
.then(response => response.json())
.then(data => {
setPhoto(data.photo.name);
});
}
}, [id, accesstoken]);
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('photo', photo);
try {
let response;
let responseData;
const options = {
method: id ? 'PATCH' : 'POST',
headers: {
'Authorization': 'Bearer ' + String(accesstoken),
},
body: formData,
};
const url = `http://xxxxxxx:8000/api/upload/${id ? `${id}/` : ''}`;
// Convert axios.post/axios.patch to fetch
response = await fetch(url, options);
responseData = await response.json();
if (id) {
setUploads((prevUploads) =>
prevUploads.map((upload) => (upload.id === responseData.id ? responseData : upload))
);
alert(`File updated successfully!`);
navigate(`/upload/${responseData.id}`);
} else {
setUploads((prevUploads) => [responseData, ...prevUploads]);
alert('Upload created successfully!');
navigate('/');
}
setPhoto(null);
} catch (error) {
console.error(error);
}
};
// ... rest of your component code remains unchanged ...
}
export default FileUpload;
请记住,通过在
.catch()
链后使用 .then()
或在异步函数中适当使用 try/catch 来处理由于网络错误而导致获取失败的可能性。这可以确保网络错误不会被捕获。
还要确保处理这些请求的服务器在处理来自不同来源的客户端请求时已正确设置为处理 CORS(跨源资源共享)。