繁体   English   中英

× 未处理的拒绝(错误):抛出了跨域错误。 React 无权访问开发中的实际错误对象

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

我正在使用上下文挂钩和减速器调度在 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

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

当通过端口或主机访问服务器时发生跨域错误(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)=>{

请记住在开发时将您的代理更改为您的基本网站名称是 EG ( 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 文档中阅读相关内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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