Search code examples
javascriptreactjsexpressrestcors

blocked by CORS on production


error + whole page

im quite new to js and had now deployed my project. in development everything was working, and so now im blocked by cors when trying to signin (registering for example works for me without a problem so i know the db is connected ). there are a few thing that i dont really understand fully and i will also provide the code sample down.

heres how i use cors + signin endpoint:

app.use(cors({
  origin:["https://almoghasson.github.io/Face-Recognition/","http://localhost:3001"],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
}));

app.post('/signin', (req, res) => {
  const { email, psw } = req.body 
  const user = { email: email } //

  postgres.select('email', 'hash').from('login')
    .where('email', '=', email) 
    .then(data => {
      const isValid = bcrypt.compareSync(psw, data[0].hash)

      if (isValid) {
        const refreshToken = uuid();
        // store token in db & cookie
        postgres.select('*').from('users')
          .where('email', '=', email)
          .update({
            token: refreshToken
          })
          .catch(err => res.status(400).json(err))

        //return user data
        return postgres.select('*').from('users')
          .where('email', '=', email)
          .then(user => {
            const { token: _, ...userWithoutRefreshToken } = user[0];
            const accessToken = generateAccessToken(userWithoutRefreshToken);
            res.cookie(REFRESH_TOKEN_COOKIE_NAME, refreshToken, { httpOnly: false, maxAge: 24 * 60 * 60 * 1000, sameSite: "none", path: '/', secure: true });
            res.json({ accessToken });
          })
          .catch(err => res.status(400).json('unable to get user'))
      } else {
        res.status(400).json('wrong credentials')
      }
    })
    .catch(err => res.status(400).json('wrong credentials'))
});

my frontend fetch:

fetch('https://face-recognition-api-n3yg.onrender.com/signin', {
            method:'post',
            headers : {
                'Content-Type':'application/json',
            },
            body: JSON.stringify({
                email: this.state.signInEmail,  
                psw: this.state.signInPsw
            }),
            credentials: 'include'
        })
        .then(res => res.json())
        .then(res => {
            if (res.accessToken){
                const user = decodeAndStoreJWT(res.accessToken);
                this.props.setBearer(res.accessToken)
                this.props.loadUser(user)
                this.props.onRouteChange('home')
                this.props.runInterval()
            }
        })

i dont get why it does not accept the origin i provided , also why is the url ".../face-recognition/" but the origin does not have this part, only "...github.io"

tried adding on the front code headers the access-allow-origin header without success
tried to set the origin in my cors to "*" without success and its not recommended anyway

EDIT: im getting this error on my server console too, if this can help:

Nov 1 06:41:45 PM  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers 
after they are sent to the client
Nov 1 06:41:45 PM      at new NodeError (node:internal/errors:372:5)
Nov 1 06:41:45 PM      at ServerResponse.setHeader (node:_http_outgoing:576:11)
Nov 1 06:41:45 PM      at ServerResponse.header (/opt/render/project/src/Backend/node_modules/express/lib/response.js:794:10)
Nov 1 06:41:45 PM      at ServerResponse.send (/opt/render/project/src/Backend/node_modules/express/lib/response.js:174:12)
Nov 1 06:41:45 PM      at ServerResponse.json (/opt/render/project/src/Backend/node_modules/express/lib/response.js:278:15)
Nov 1 06:41:45 PM      at /opt/render/project/src/Backend/server.js:86:45
Nov 1 06:41:45 PM      at processTicksAndRejections (node:internal/process/task_queues:96:5) {
Nov 1 06:41:45 PM    code: 'ERR_HTTP_HEADERS_SENT'
Nov 1 06:41:45 PM  }

Solution

  • Try setting the origin in lowercase as the browser sends it this way. If you use https://almoghasson.github.io/face-recognition, it works (as you can see in the screenshot below).

    Furthermore, looking at your request, the origin appears to be only "https://almoghasson.github.io/".

    Actual origin

    So, you would like to use https://almoghasson.github.io instead of https://almoghasson.github.io/Face-Recognition/

    app.use(cors({
      origin:["https://almoghasson.github.io", "http://localhost:3001"],
      allowedHeaders: ['Content-Type', 'Authorization'],
      credentials: true,
    }));
    

    Here the test:

    CORS check