Home > Blockchain >  Reactjs, CORS errors while making post request using axios
Reactjs, CORS errors while making post request using axios

Time:07-14

I am using React.js 18 version. Facing CORS issue on a piece of code while making post request using axios. Intentionally not putting the original URL of post request. Attaching API response screenshot files below the code.

I am getting response in postman but not in browser(CORS). All I know from my colleague, this API is build on PHP and according to backend guy things are fine on his side.
I am putting this code here to know what are we doing wrong on front end? We are stuck here since yesterday. Please help!

console response : https://i.stack.imgur.com/HbUjq.png network response : https://i.stack.imgur.com/6xycq.png network response : https://i.stack.imgur.com/5cjey.png postman response : https://i.stack.imgur.com/MxyDT.png

import React, {useState, useEffect} from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [CaseDetail, setCaseDetail] = useState([]);

  const getCaseDetail = async () => {
const casedetail = {schemeNameDratDrtId:'1',casetypeId:'1',caseNo:'1',caseYear:"2020"}; 
    await axios.post('URL', casedetail,
    {
      headers: {"Access-Control-Allow-Origin": "*"}
    } 
    )
    .then((result) => {
      setCaseDetail(result.data.data)
      })
   }

   useEffect(() => {
    getCaseDetail();  
  }, []);
  console.log(CaseDetail)

  return (
    <div className="App">
      <h2>Welcome to Home Page</h2>
    </div>
  );
}

export default App;

CodePudding user response:

Your server should enable the cross-origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms

CodePudding user response:

This is a security issue from the browser. If you get 200 using postman, this means the problem is that the browser is blocking it. Try to play this again using API testing website like: "reqbin.com", if that works, the backend guys can fix the header problem. I hope this helps.

  • Related