Search code examples
reactjsnode.jsaxioscorsfastify

Unable to get information from server with axios and cors


I recently made a node server using fastify and now im trying to integrate it with my react front end with axios, so im using as well cors in the backend to allow access, but im getting the following error: enter image description here

Here is my Node server code:

import fastify from 'fastify'
import cookie from '@fastify/cookie'
import websocket from '@fastify/websocket'
import { createPoll } from './routes/create-poll'
import { getPoll } from './routes/get-poll'
import { voteOnPoll } from './routes/vote-on-poll'
import { pollResults } from './ws/poll-results'
import cors from '@fastify/cors'

const app = fastify()

app.register(cors, {
    origin: true
})

app.register(cookie, {
    secret: "polls-app-nlw-lrc",
    hook: 'onRequest',
})

app.register(websocket)

app.register(createPoll)
app.register(getPoll)
app.register(voteOnPoll)
app.register(pollResults)

app.listen({port: 3333}).then(()=> {
    console.log('HTTP server running!')
})

And my the part of my react code with axios:

import axios from "axios"

const api = axios.create({
    baseURL: 'http://localhost:3333'
  })

export function Select(){
    api.get('/polls/:pollId').then( (response) => {
        console.log(response)
    })

    return()}

I removed the return content because i dont think its the problem since i barely started to integrate. Someone know how to fix it? I thought that what was wrong was the app.register cors in the Node code or calling it in const api in the react code but i checked the adresses already and tried following fastify cors documentation but didnt worked. Node server, docks and react app are all running as well.


Solution

  • The 500 error code seems to come from this part of the code api.get('/polls/:pollId'). This is not a cors error as a cors error would also give a network error and display a message in the console. Error 500 means an internal server error. Assuming the route is properly set up on the backend you should replace :pollId with the id of the element you want to retreive.