简体   繁体   English

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

[英]× 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.我正在使用上下文挂钩和减速器调度在 React 中创建一个注销链接。 I'm getting an error after i log-in.我登录后出现错误。

I'm using node, express, and mongoose in the backend.我在后端使用 node、express 和 mongoose。

Here is Logout.js:这是 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:这是 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.这是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

Here is Sidebar.js :这是 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:在浏览器控制台中,有 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

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 )当通过端口或主机访问服务器时发生跨域错误(React 而不是 localhost 或www.websitename.com

To quickly fix this, add this to your React package.json:要快速解决此问题,请将其添加到您的 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.您现在可以使用“/”而不是“http://localhost:2000”访问服务器文件,因为 React 使用的是代理而不是外部链接。

Your code in Logout.js line 7 should now be:您在 Logout.js 第 7 行中的代码现在应该是:

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 )请记住在开发时将您的代理更改为您的基本网站名称是 EG ( www.website.com )

EDIT: for convenience, the Logout.js full code can be replaced with:编辑:为方便起见,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

If this doesn't work, try our the cars npm package at https://www.npmjs.com/package/cors如果这不起作用,请在https://www.npmjs.com/package/cors尝试我们的汽车 npm 包

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.重要说明 - 在生产中使用 cors 时,请确保传入这样的对象 {origin: YOUR_REACT_LOCALHOST_URI}。 You can read up on this in the cors npm docs.您可以在 cors npm 文档中阅读相关内容。

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

相关问题 错误:引发了跨域错误。 React 无法访问开发中的实际错误 object - Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development 引发了跨域错误。 react 无权访问 react 开发中的实际错误 object - A cross-origin error was thrown. react doesn't have access to the actual error object in development in react "<i>Uncaught Error: A cross-origin error was thrown.<\/i>未捕获的错误:引发了跨域错误。<\/b> <i>React doesn&#39;t have access to the actual error object in development<\/i> React 无法访问开发中的实际错误对象<\/b>" - Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development 未捕获的错误:在 React 中抛出跨源错误 - Uncaught Error: A cross-origin error was thrown in React 为什么 postman 不会出现跨域块错误? - why postman doesn't get cross-origin block error? Codesandbox.io 引发了跨域错误问题 - A cross-origin error was thrown problem with Codesandbox.io React js tsx codesandbox问题 抛出了跨域错误,lodash.isequal - React js tsx codesandbox problem A cross-origin error was thrown and lodash.isequal getImageData跨源错误 - getImageData cross-origin error 跨域请求错误 - cross-origin request ERROR 不确定跨域错误的来源 - Unsure as to Origin of Cross-origin Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM