JS returning No 'Access-Control-Allow-Origin'

Related searches

I'm having some unusual problems with my React app about Access-Control-Allow-Origin. I had problems like this with login/register system and I fixed it (obviously not). Now I have problems with getting user information. In the same file where I have my login, register I have a function to grab user info, when I console.log it's giving me No 'Access-Control-Allow-Origin' with Request, Method: OPTIONS, Status Code: 403 Forbidden, and my code look like this.

export const getProfile = () => {
    return axios
        .get('api/user', {
            headers: { Authorization: `Bearer ${localStorage.token}` }
        })
        .then(response => {
            console.log(response)
            return response.data
        })
        .catch(err => {
            console.log(err)
        })
}

I'm using Laravel API, I have a function for handling CORS, I had difficulties with login/register and it was the same problem, I fixed it and CORS is obviously not handling well or there is something wrong? When I try in Postman everything works fine.

This is how login form looks like.

export const userSignIn = ({email, password}) => {
  return (dispatch) => {
    dispatch({type: FETCH_START});
    axios.post('api/login', {
        email: email,
        password: password,
      }
    ).then(response => {
     if (response.data.success) {
        localStorage.setItem("token", JSON.stringify(response.data.token));
        axios.defaults.headers.common['access-token'] = "Bearer " + response.data.token;
        dispatch({type: FETCH_SUCCESS});
        dispatch({type: USER_TOKEN_SET, payload: response.data.token});
      } else {
        dispatch({type: FETCH_ERROR, payload: response.data.message});
      }
    }).catch(function (error) {
      dispatch({type: FETCH_ERROR, payload: error.message});
      console.log("Error****:", error.message);
    });
  }
};

Even if I install chrome extension to block CORS, still same error, just there is not message that is blocked by cors because of headers.

return, Disallows unnecessary return await (no-return-await). Using return await inside an async function keeps the current function in the call stack until the Promise� The return statement stops the execution of a function and returns a value from that function. Read our JavaScript Tutorial to learn all you need to know about functions. Start with the introduction chapter about JavaScript Functions and JavaScript Scope.

Are you testing the endpoint on Postman(example) if is working well ?

Can you post your CORS ?

Probably iś the error on CORS config

Functions, A confusing aspect of JavaScript is that a function returns undefined if any of the following are true: it does not execute a return statement before it exits� JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running. JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return keyword.

first of all, You are trying to get a token from local storage, you should write like this:

localStorage.getItem('token')//make sure 'token' is the name you saved in local storage

try adding the following code in the headers along with "Authorization" and check if it works:

"Access-Control-Allow-Origin": "*"

if it does not work, add more in headers

 headers: { "X-Custom-Header": "foobar", "Access-Control-Allow-Origin": "*",Authorization: `Bearer ${localStorage.getItem(token)}` },

Functions :: Eloquent JavaScript, Comparing two JavaScript objects will always return false. Complete Boolean Reference For a complete reference, go to our Complete JavaScript Boolean Reference .

no-return-await - Rules - ESLint, In JavaScript, most functions are both callable and instantiable: they have both a and [[Construct]] internal methods. As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value. var player = makeGamePlayer("John Smith", 15, 3);

consistent-return - Rules - ESLint, When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement. Functions often compute a return value. The return value is "returned" back to the "caller":

There are no more nested calls, so the function finishes, returning 2. As the function finishes, its execution context is not needed anymore, so it’s removed from the memory. The previous one is restored off the top of the stack: Context: { x: 2, n: 2, at line 5 } pow(2, 2) Context: { x: 2, n: 3, at line 5 } pow(2, 3)

Comments
  • CORS is a issue that has to be solved from the server side by adding few headers to the response API and handling the OPTIONS request. Search for an Laravel CORS middleware and add it to your codebase for easier approach.
  • Yes, I have cors installed on my laravel app, works fine with other functions
  • This isn't an answer.
  • I don't think it is about cors config. Here it how it looks like 'supportsCredentials' => false, 'allowedOrigins' => [''], 'allowedHeaders' => ['Content-Type', 'X-Requested-With'], 'allowedMethods' => [''], // ex: ['GET', 'POST', 'PUT', 'DELETE'] 'exposedHeaders' => [], 'maxAge' => 0, ---------------------------
  • Thank you for joining in on the discussion here. However please use comments to ask clarifying questions like this otherwise it can create confusion in the process of trying to help Rade with their problem. See answering guidelines for more info.
  • The Access-Control-Allow-Origin header has to come from the server in the response, not the client in the request.
  • it works at least when I was working with backend developers.
  • This doesn't work. I put the login form in post maybe it could help to see what is the problem :)
  • It sounds like you need to whitelist the connection to your API on the server side to allow connections from whatever port/domain your UI is running on.