简体   繁体   中英

× Unhandled Rejection (Error): A cross-origin error was thrown. React doesn't have access to the actual error object in development

I'm creating a logout link in React using context hooks and reducer dispatch. I'm getting an error after i log-in.

I'm using node, express, and mongoose in the backend.

Here is Logout.js:

 import React ,{useState, useContext}from 'react'; import {useHistory,Redirect, Link} from 'react-router-dom' import { AuthContext } from '../../contexts/AuthContext'; import axios from 'axios' const Logout =()=>{ const {authLog,dispatch} = useContext(AuthContext) axios.get('http://localhost:2000/apiEndpoint/CREATE/user/logout',{withCredentials:true}).then((res)=>{ if(res.data==='Logout Success'){ dispatch({type: 'LOGOUT'}); } }).catch((err)=>{ console.log(err) }) return( <div > <h1>You are logged out!!!!</h1> {<Redirect to='/' />} </div> ) } export default Logout

Here is AuthReducer.js:

 import React from 'react'; const AuthReducer = (state, action) => { switch (action.type) { case "LOGIN": localStorage.setItem("user", JSON.stringify(action.payload.user)); localStorage.setItem("token", JSON.stringify(action.payload.token)); return { ...state, isAuthenticated: true, user: action.payload.user, token: action.payload.token }; case "LOGOUT": localStorage.clear(); return { ...state, isAuthenticated: false, user: null }; default: return state; } }; export default AuthReducer

Here is Blog.js: [NOTE] : I'm getting an error after the login page when it redirects me to the Blog.js component after successful login.

 import React, { Component } from 'react'; import ArticleCard from '../ArticleCard' import '../CSS/Blog.css' import Sidebar from './Sidebar'; const axios = require('axios').default; class Blog extends Component{ state={ } render(){ return ( <div className='blog-grid'> <div className='ninetyPer'> <ArticleCard /> </div> <div className='tenPer'> <Sidebar /> </div> </div> ) } } export default Blog

Here is Sidebar.js :

 import React ,{useState, useContext}from 'react'; import {useHistory,Redirect, Link} from 'react-router-dom' import { AuthContext } from '../../contexts/AuthContext'; import '../CSS/Sidebar.css' const Sidebar =()=>{ const {authLog,dispatch} = useContext(AuthContext) var userOBJ=(authLog.isAuthenticated)?(JSON.parse(authLog.user.userLocal)):null; console.log('AuthLOg:',userOBJ) return( <div className='sidebar'> {userOBJ!=null?(<h4>Hello {userOBJ.username}!</h4>):(<h4>You are not logged in</h4>)} {authLog.isAuthenticated?(<Link to='/user/logout'><h5>Logout</h5></Link>):''} <hr /> </div> ) } export default Sidebar

In the browser console, there are 3 error including the one in the title:

 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at Sidebar (Sidebar.js:14) at renderWithHooks (react-dom.development.js:14803) at mountIndeterminateComponent (react-dom.development.js:17482) at beginWork (react-dom.development.js:18596) at HTMLUnknownElement.callCallback (react-dom.development.js:188) at Object.invokeGuardedCallbackDev (react-dom.development.js:237) at invokeGuardedCallback (react-dom.development.js:292) at beginWork$1 (react-dom.development.js:23203) at performUnitOfWork (react-dom.development.js:22154) at workLoopSync (react-dom.development.js:22130) at performSyncWorkOnRoot (react-dom.development.js:21756) at react-dom.development.js:11089 at unstable_runWithPriority (scheduler.development.js:653) at runWithPriority$1 (react-dom.development.js:11039) at flushSyncCallbackQueueImpl (react-dom.development.js:11084) at flushSyncCallbackQueue (react-dom.development.js:11072) at scheduleUpdateOnFiber (react-dom.development.js:21199) at dispatchAction (react-dom.development.js:15660) at Login.js:39 index.js:1 The above error occurred in the <Sidebar> component: in Sidebar (at Blog.js:29) in div (at Blog.js:28) in div (at Blog.js:21) in Blog (created by Context.Consumer) in Route (at App.js:43) in AuthContextProvider (at App.js:38) in Switch (at App.js:37) in Router (created by BrowserRouter) in BrowserRouter (at App.js:33) in div (at App.js:31) in App (at src/index.js:9) in StrictMode (at src/index.js:8) Consider adding an error boundary to your tree to customize error handling behavior. Visit //fbReactLink to learn more about error boundaries. console.<computed> @ index.js:1 react-dom.development.js:248 Uncaught (in promise) Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development. See //fbReactLink for more information. at Object.invokeGuardedCallbackDev (react-dom.development.js:248) at invokeGuardedCallback (react-dom.development.js:292) at beginWork$1 (react-dom.development.js:23203) at performUnitOfWork (react-dom.development.js:22154) at workLoopSync (react-dom.development.js:22130) at performSyncWorkOnRoot (react-dom.development.js:21756) at react-dom.development.js:11089 at unstable_runWithPriority (scheduler.development.js:653) at runWithPriority$1 (react-dom.development.js:11039) at flushSyncCallbackQueueImpl (react-dom.development.js:11084) at flushSyncCallbackQueue (react-dom.development.js:11072) at scheduleUpdateOnFiber (react-dom.development.js:21199) at dispatchAction (react-dom.development.js:15660) at Login.js:39

If you need me to post the other components as well please do let me know and I will update this post.

A cross-origin error occurs when the server is being accessed through a port or host other than itself (React rather than localhost or www.websitename.com )

To quickly fix this, add this to your React package.json:

"proxy": "http://localhost:2000"

You can now access the server files using "/" instead of "http://localhost:2000" as React is using the proxy instead of an external link.

Your code in Logout.js line 7 should now be:

axios.get('/apiEndpoint/CREATE/user/logout',{withCredentials:true}).then((res)=>{

Just remember to change your proxy when in development to whatever your base website name is EG ( www.website.com )

EDIT: for convenience, the Logout.js full code can be replaced with:

import React ,{useState, useContext}from 'react';
import {useHistory,Redirect, Link} from 'react-router-dom'
import { AuthContext } from '../../contexts/AuthContext';
import axios from 'axios'

const Logout =()=>{
    const {authLog,dispatch} = useContext(AuthContext)
 axios.get('/apiEndpoint/CREATE/user/logout',{withCredentials:true}).then((res)=>{
     
      if(res.data==='Logout Success'){
        dispatch({type: 'LOGOUT'});
        
      }
  }).catch((err)=>{
      console.log(err)
  })
    

    return(
        <div >
            <h1>You are logged out!!!!</h1>
            {<Redirect to='/' />}
        </div>
        
    )
}


export default Logout

If this doesn't work, try our the cars npm package at https://www.npmjs.com/package/cors

Simply import it and run the function right after initializing app as follows

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

IMPORTANT NOTE -- make sure to pass in an object like this {origin: YOUR_REACT_LOCALHOST_URI} when using cors in production. You can read up on this in the cors npm docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM