【问题标题】:× Unhandled Rejection (Error): A cross-origin error was thrown. React doesn't have access to the actual error object in development× Unhandled Rejection (Error):抛出了跨域错误。 React 无法访问开发中的实际错误对象
【发布时间】:2020-10-13 14:49:32
【问题描述】:

我正在使用上下文挂钩和减速器调度在 React 中创建一个注销链接。登录后出现错误。

我在后端使用 node、express 和 mongoose。

这里是 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

这里是 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

这是 Blog.js: [注意]:登录页面后我在成功登录后将我重定向到 Blog.js 组件时出现错误。

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

这里是 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

在浏览器控制台中,包括标题中的错误在内有 3 个错误:

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

如果您还需要我发布其他组件,请告诉我,我会更新这篇文章。

【问题讨论】:

    标签: javascript json reactjs react-hooks


    【解决方案1】:

    当服务器通过自身以外的端口或主机(React 而不是 localhost 或 www.websitename.com)访问服务器时,会发生跨域错误

    要快速解决此问题,请将其添加到您的 React package.json:

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

    您现在可以使用“/”而不是“http://localhost:2000”访问服务器文件,因为 React 使用的是代理而不是外部链接。

    Logout.js 第 7 行中的代码现在应该是:

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

    只要记住在开发时将您的代理更改为您的基本网站名称是 E.G. (www.website.com)

    编辑:为方便起见,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('/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
    

    如果这不起作用,请在https://www.npmjs.com/package/cors 尝试我们的汽车 npm 包

    在初始化应用程序后直接导入并运行函数,如下所示

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

    重要提示——在生产环境中使用 cors 时,请确保传入像 {origin: YOUR_REACT_LOCALHOST_URI} 这样的对象。 您可以在 cors npm 文档中阅读此内容。

    【讨论】:

    • 感谢您的回复,但遗憾的是没有奏效。我得到了完全相同的错误。
    • 刚刚使用替代解决方案进行了更新。注意底部的注释
    • 我试过了。我已经在 cors 中将 origin 设置为 true。谢谢。
    猜你喜欢
    • 2021-11-18
    • 2020-07-15
    • 2018-07-14
    • 2021-02-19
    • 2023-02-15
    • 2012-04-03
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多