-1

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;
neil
  • 11
  • 4

3 Answers3

0

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

Sathiyaraj
  • 343
  • 3
  • 11
-1

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 should fix the header problem. I hope this helps.

-1

some possiable things that might help:

  1. I am getting response in postman but not in browser(CORS) - this is noraml for CORS problem.

  2. there can be a differnce betweeen fetach and axios requests. so check if fetach works. if so check

Axios fails CORS but fetch works fine

  1. if you need to send a token in a header , make sure that the axios sends it

see How to set header and options in axios?

Citizen-Dror
  • 843
  • 9
  • 17