Can someone help me translate these axios requests into fetch requests? I am having trouble transfering the token in axios. I think it would work in fetch but I am having trouble rewriting the request.
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;
I have tried to represent the token system wide with axios interceptor.
I have tried to include token in each request with
`'Authorization':'Bearer ' + String(authTokens.access).`
I have one request written in fetch and it works with
`'Authorization':'Bearer ' + String(authTokens.access).`
2
Answers
Below is how you would convert the given Axios requests to
fetch
requests in JavaScript. Note that for both GET and PATCH/POST requests with fetch, we’re adding the'Authorization': 'Bearer ' + accesstoken
header for token-based authentication.Remember to handle the possibility that the fetch could fail due to network errors by using a
.catch()
after the.then()
chains or using try/catch appropriately within an async function. This ensures that network errors do not go uncaught.Also ensure that the server handling these requests is properly set up to handle CORS (Cross-Origin Resource Sharing) when dealing with client-side requests from a different origin.
Try this.