简体   繁体   中英

origin http://localhost:3000 has been blocked by CORS policy: The Access-Control-Allow-Origin In my react App

I am beginner of react program. I am just building one small web app using Laravel and React. I suddenly got error I don't know what I did wrong. If anyone help me I will be glade to you. Bellow the error message:

Access to XMLHttpRequest at http://127.0.0.1:8000/sanctum/csrf-cookie from origin http://localhost:3000 has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value http://localhost:4200 that is not equal to the supplied origin.

I am trying like this way:

import React from 'react';
import { BrowserRouter as Router, Route, Switch} from 'react-router-dom';

import MasterLayout from './layouts/admin/MasterLayout';

import Home from './components/frontend/Home';
import Login from './components/frontend/auth/Login';
import Register from './components/frontend/auth/Register';
import axios from 'axios';

axios.defaults.baseURL = "http://127.0.0.1:8000";
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Accept'] = 'application/json';
axios.defaults.withCredentials = true;
    
function App() {
  return (
    <div className="App">
        <Router>
          <Switch>
            {/* Homepage */}
            <Route exact path="/" component={Home}/>

            {/* Auth Pages */}
            <Route path="/login" component={Login}/>
            <Route path="/register" component={Register}/>


            <Route path="/admin" name="Admin" render={(props) => <MasterLayout {...props} />} />

          </Switch>
        </Router>
    </div>
  );
}

export default App;

CORS is a browser mechanism that asks webserver if it is willing to accept request from specific origin. Origin is your hostname + port, meaning localhost:3000 , localhost:4200 and localhost:8000 are all different origins.

You can either configure header Access-Control-Allow-Origin on your backend side to accept requests from 'localhost:3000', or you can start your react application on port :4200 , since it is already accepted by your backend, or you can use proxy that will make requests to backend from server side.

In production environment you usually have backend and frontend working on same origin, so proxy is a good way to solve CORS problems during development. You also can setup some reverse proxy, like nginx, so your backend and frontend would both be on same origin.

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