2

I am trying to get data from api using axios but i am getting this error. I am using django api. my api seems to be working fine on postman but with react it is giving me the error:

getStudentById(id) {
        const url = `${API_URL}/api/student/student-detail/${id}`;
        return axios.get(url);
    }

componentDidMount() {
     let urlId = this.props.match.params.id;
     
    let thisComponent = this;
    studentService.getStudentById(urlId)
      .then(function (response)  {
        console.log(response.data.Name)
         thisComponent.setState({
            id: response.data.id, 
            name: response.data.Name,
            enrollment_no: response.data.Enrollment_No,
            registration_no:response.data.Registration_No,
            semester: response.data.Semester,
            year: response.data.Year,
            course_nam: response.data.Course_Name,
            course_code: response.data.Course_Code,
            images: response.data.images
           });
          
      }).catch(error=>console.log(error))
     
  }

error screenshot

Bushra Akram
  • 31
  • 1
  • 1
  • 5

2 Answers2

0

These errors may be caused due to follow reasons, ensure the following steps are followed. To connect the local host with the local virtual machine(host). Here, I'am connecting http://localhost:3001/ to the http://abc.test Steps to be followed:

  1. We have to allow CORS, placing Access-Control-Allow-Origin: in header of request may not work. Install a google extension which enables a CORS request.*
  2. Make sure the credentials you provide in the request are valid.
  3. Make sure the vagrant has been provisioned. Try vagrant up --provision this make the localhost connect to db of the homestead.
  4. Try changing the content type of the header. header:{ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' } this point is very important.
ganicvp7
  • 47
  • 4
0

I had a similar mistake. (Django + Vue)

In the "settings.py" file, I had CORS_ALLOWED_ORIGIN, instead of CORS_ALLOWED_ORIGINS :)

CORS_ALLOWED_ORIGINS = [
"http://127.0.0.1:8080",
]
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/31505113) – Brian Patterson Apr 15 '22 at 04:46