Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

516
Visualizações
cors wont work even if Access-Control-Allow-Origin is set to *

I am working in a tiny project in react and express.js

the express.js code (Backend)

app.post('/api/search', (req, res) => { 
    // 
    res.setHeader("Access-Control-Allow-Origin", "*");
    axios.get("[REDACTED]" + req.body.searchtxt + "&limit=100").then((response) => {
        res.json({status: "ok", result: response.data})
    })

    
})

and here the front-end

function SearchPage() {
    const { searchText } = useParams()
    const [SearchTxt, setSearchTxt] = useState(searchText)
    useEffect(()=>{
        fetch('http://localhost:8080/api/search', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            mode: 'cors',
            body: JSON.stringify({searchtxt: searchText})
        }).then((res) => {
                res.json().then((resjson) => {
                    console.log(resjson)
                })
            })
    },[])
}

but it shows this :

Access to fetch at 'http://localhost:8080/api/search' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't pass access control
check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an
opaque response serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.

I've tried with Access-Control-Allow-Origin set to localhost:3000 but it don't work

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Browser sends OPTIONS preflight requests by default when sending a request. So, you should send Access-Control-Allow-Origin header for that request as well.

The easiest solution is to use cors middleware package. You can use it like this:

const cors = require('cors');

app.post('/api/search', cors(), (req, res) => { 

  res.setHeader("Access-Control-Allow-Origin", "*");
  axios.get("[REDACTED]" + req.body.searchtxt + "&limit=100").then((response) => {
    res.json({status: "ok", result: response.data})
  })

})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda