1

I am trying to send a post request to my api, however I am getting a 422 response. In insomnia, using the exact same body and everything, I am able to successfully make the request, so I am unsure why my code doesn't do the exact same.

    const[stopinfo, setStopInfo] = useState([]);

const requestOptions = {
    method: 'POST',
    body: JSON.stringify({ 
        'min_date': startDate,
        'max_date': endDate,
        'min_time': '00:00:00',
        'max_time': '23:00:00',
        'bus_ids': [2,3,4],
        'route_ids': [1,2,3]
     })
};

const fetchStopData = async () => {
fetch("https://mywebsite.com/api/data/stopinfo", requestOptions).then(response => response.json())
.then(data => setStopInfo(data))
    }

useEffect(() => {
    fetchStopData()
  },[]);

error message insomnia

Jack A
  • 109
  • 1
  • 4
  • 10
  • remove quotations from your object key, or don't stringify it. – Farbod Shabani Nov 17 '22 at 14:39
  • 1
    @FarbodShabani that will not accomplish anything. In fact, if you're supplying JSON, you're supposed to pass in JSON, not an object. Other valid values are Blob, or a URLSearchParames, depending on the type of request made. – VLAZ Nov 17 '22 at 14:44
  • What is the value of `startDate` and `endDate` in your request body? – vighnesh153 Nov 17 '22 at 14:44
  • 2
    I think `headers: { 'Content-Type': 'application/json' }` is missing in `requestOptions` – VLAZ Nov 17 '22 at 14:45
  • @VLAZ i did try adding that earlier and got an error - "Access to fetch at 'https://mywebsite/api/data/stopinfo' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status." I have my private key set up already. – Jack A Nov 17 '22 at 15:35
  • Then you have a cors issue. there are thousands of questions like that on SO. – Evert Nov 17 '22 at 17:02
  • Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – Evert Nov 17 '22 at 17:02
  • @Evert I fixed the cors issue and still get a 422 error. – Jack A Nov 17 '22 at 18:05
  • Show the headers, including the payload to the server. Your screenshot shows a js object under the JSON tab which makes the whole question ambiguous. – morganney Nov 17 '22 at 22:11
  • @morganney i don't understand. I have updated my code to include the content type header, but I am passing that exact data in insomnia via POST and it returns back my JSON data. – Jack A Nov 18 '22 at 01:51

0 Answers0