简体   繁体   中英

I get an error xxx has been blocked by CORS policy in React

I'm making a system that can login with email and password with React.js. The backend (REST API) has already been completed by the client The following error message occurred while implementing the code below. I'm not sure URL of the API received from the client is bad or the client needs to edit the CORS settings on the backend side? I was a little unsure, so I asked the question. Also, if something weird on my code, please give me advice.

The error is

Access to XMLHttpRequest at 'https://login.xxx.com/login' from origin 'http://localhost:3002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The whole code is below.

import React, { useState, useEffect, useRef } from 'react';
import { useCookies } from 'react-cookie';
import axios from 'axios';
import { useForm } from "react-hook-form";
import  { useHistory } from 'react-router-dom';
import { apiURL } from './Default';
import logo_image from "../images/logo/logo.png";
import { useParams, Link } from 'react-router-dom'
import { useDispatch } from "react-redux";
import background from "../images/background/BG.png";
import '../App.css';

import { isLoggedInOn } from "../stores/user";
import { setUserID } from "../stores/user";

const Login = () => {
  const history = useHistory();
  const dispatch = useDispatch();
  const [cookies, setCookie] = useCookies();
  const { register, handleSubmit, watch, errors } = useForm();
  
  const getJwt = async (data) =>{

        console.log(data)

        await axios.post(`https://login.xxx.com/login`,
          {
            username:data.email,
            password:data.password,
          },

        )

        .then(function (response) {

          console.log(response.data.access)

          setCookie('accesstoken', response.data.access, { path: '/' }, { httpOnly: true });

          setCookie('refreshtoken', response.data.refresh, { path: '/' }, { httpOnly: true });

          dispatch(isLoggedInOn());

          history.push('/');
        })
        .catch(err => {
            console.log("miss");
            alert("Email or Password is wrong!");
        });
      };

  return (
    <div className="container">
    <div className="row mx-auto">
      <div className="col-md-4 mx-auto text-center">
          <div className="row mx-auto logo_image">
            <img className="" src={logo_image} alt="" />
          </div>
          <div className="login-block">
            <form onSubmit={handleSubmit(getJwt)}>
              <input placeholder='Email Address' className='form-control' {...register('email')} />
              <input placeholder='Password' className='form-control' type="password" {...register('password', { required: true })} />
              <Link to={`/`} style={{color: "white"}}>Reset password</Link><br></br>
              <input className='btn btn-block btn-primary col-12' type="submit" value="Login" />
            </form>
          </div>
          <div className="register-block">
            <p style={{color: "white"}}>Don't have an account yet?</p>
            <Link to={`/signup`} className='btn btn-secondary col-12'>Register</Link>
          </div>
      </div>
    </div>
    </div>




  );
}
export default Login;

This is not a solution for when you deploy to serve, but for local development, inside the package.json you can set the property "proxy": "https://login.xxx.com/" this will remove the CORS error.

{
  "name": "flickr-client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "^2.1.8"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:4000"
}

Reference here

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