DEV Community

Subho Karmakar
Subho Karmakar

Posted on

Help me solve this CORS Policy Issue - React App

I'm trying to delete a user by id from server, accessing the api with axios http client on react app and receiving this message in developer/ console ->

Access to XMLHttpRequest at 'host:8082/user/delete/6' from origin 'localhost:3000' 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.

Here's my code -

import React from "react"
import axios from "axios"

export default class PersonList extends React.Component {
  state = {
    id: "",
  }

  handleChange = event => {
    this.setState({ id: event.target.value })
  }

  handleSubmit = event => {
    event.preventDefault()

    axios
      .delete(`http://host:8082/user/delete/${this.state.id}`)
      .then(res => {
        console.log(res)
        console.log(res.data)
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit} crossOrigin="anonymous">
          <label>
            User ID:
            <input type="text" name="id" onChange={this.handleChange} />
          </label>
          <button type="submit">Delete</button>
        </form>
      </div>
    )
  }
}

Please help me to resolve this cors issue.

Top comments (2)

Collapse
 
bchhun profile image
Bernard Chhun

Hi Subho,

You need to change the CORS settings on your local backend server so that it can received requests from the localhost http address.

I can't tell you how since you're not mentionning what backend tech you are using :)

Collapse
 
jacobmgevans profile image
Jacob Evans

What's in your headers your sending to the backend? Also, what are you using for a backend?