-2
import React, { useState, useEffect } from 'react'
import axios from 'axios'

const Test = () => {
  const [data, setData] = useState()
  useEffect(() => {
    const fetchData = async () => {
      const url = 'https://test.secure.app/api'
      const response = await axios.get(url)
      console.log('Response', response)
      console.log('Data', response.data)

      const jsonData = response.json()
      console.log('jsonData', jsonData)
      setData(jsonData)
    }

    fetchData()
  }, [])

  return <>{data}</>
}

export default Test

When code is executed, I am receiving CORS issue.

Can we try resolving CORS issue from client-side? If yes, can you please suggest and share available methods for reference?

Error: Access to XMLHttpRequest at 'https://test.secure.app/api' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Does this answer your question? [React Client Cors issue](https://stackoverflow.com/questions/73458894/react-client-cors-issue) – jabaa Jun 24 '23 at 16:03

1 Answers1

1

No, this cannot be fixed client side only, because browsers will respect the headers on what you're requesting. This is also clear from the error message.

No 'Access-Control-Allow-Origin' header is present on the requested resource

Think about it, why would CORS even exist if you could circumvent it without the origin's approval?

While there are ways to modify your browser configuration to have it not check CORS, it's not a viable strategy as you can obviously not do this with other people's browsers. I would also advice against relying on that for local development, as everybody who develops on that application would need to also reduce their browser security. If you're really under time pressure, it could be a temporary solution though.

What eventually has to happen to be able to turn this into a viable product, is the server you're requesting from has to either allow all origins, or specifically the origin your code will be running on. So it's crucial to confirm that you'll ever be able to do this. How exactly you would configure that depends on the API server and is beyond the scope of this question.

inwerpsel
  • 2,677
  • 1
  • 14
  • 21