skip to Main Content

I am sending a request to an endpoint but its not coming with a response but the endpoint is available. Here is my code.


import './App.css'
import React,{useState,useEffect} from 'react'
import Dashboard from './Dashboard'
import Login from './login/Login'
import axios from 'axios'



export default function App() {
  
const[isLogged,setIsLogged] = useState(false);


  const[csrf,setCsrf] = useState("");

  const url = 'https://mtstorez.000webhostapp.com/app/store/welcome'

  
  //get login status of user
  useEffect(() => {
    axios.post(url, {
      key1: 'value1',
      key2: 'value2'
    })
    .then(response => {
      console.log('AJAX request successful');
      //setData(response.data);
    })
    .catch(error => {
      console.log('AJAX request failed');
      //setError(error.message);
    });
  }, []);



  
  return (

  
    <main>

      {
        isLogged ? <div> <Dashboard/> </div> :
      <Login/>
      }
    </main>
  )
}


I tried jsonplaceholder endpoint to generate fake data and it worked. I also allowed request from all origin and it didn’t work also.

Thanks for your help in advance

2

Answers


  1. As I see that endpoint required form data, not JSON. This works fine for me

      useEffect(() => {
        const formData = new FormData();
        formData.append("key1", "value1");
        formData.append("key2", "value2");
    
        axios
          .post(url, formData)
          .then((res) => console.log(res))
          .catch((err) => console.log(err));
      }, []);
    
    Login or Signup to reply.
  2. I’ve tried your endpoint using postman and got back a proper response both with POST and GET.

    However, when tried from a browser, only the GET request performs as expected. I’ve set up a reproductible example here :https://github.com/jbrocher/question-76220440. The POST version fails with a preflight error.

    The difference of behavior between postman and the browser points to a CORS issue.

    From the test I’ve done with Postman, it would seem the endpoint returns the same thing both using GET and POST so I would suggest using the GET version as I did in the repository I linked. I you have control over the endpoint, should verify your CORS settings as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search