Issues in implementing Rob-W's CORS anywhere to make post request with authentications work

154 Views Asked by At

I am making a React application, and very recently, I am trying to call API requests to the Back-end server. The problems emerged when I try to include credentials into the headers of my API requests, when the the browser throws an error that says they cannot fetch it The error that occurs

Upon closer investigation, I realized that it was a CORS issue (as seen in the preflight request), so I used the demo version of cors-anywhere, and to my surprise it allowed to send the request. Instance of cors-anywhere working

Although this works, I am fully aware that this cannot last for long, as the demo server is public.

import React from "react";
import useAuth from "../../Hooks/useAuth";

export default function UploadJSX(){
    const {auth} = useAuth();
    const token = auth.accessToken;
    
    const uploadPost = async () =>{
        await fetch(`https://cors-anywhere.herokuapp.com/https://initiare-website-2603191647bb.herokuapp.com/api/v1/articles`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + token
              },
              body: JSON.stringify({
                content: "Uploaded via cors-anywhere"
              })
            }
          )
    }
    return(
        <>
            <button onClick={uploadPost}>Upload a post right here</button>
        </>
    )
}

I do not know how to start, or what to do regarding this problem. Is there any way I can resolve this without the use of cors-anywhere, like meddling with proxies for example? Either way, as I am purely Front-end, I am not too sure if this is a back-end problem or not, because the APIs called on Postman works just fine. I'm also unsure whether it could be implemented entirely in Front-end.

1

There are 1 best solutions below

0
On

I have solved this issue not by using cors-anywhere, but by putting " mode: 'cors' " in the fetching object next to the URL. the fetching now works great with authorization. It is kinda sad that I spent 4 days looking for a solution when the fix is literally 1 line of code