nopasteonlybin

cookie problem

Oct 14th, 2022 (edited)
441
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // SERVER CODE TO BE PUT INSIDE NODE APP
  2. const cors = require('cors')
  3. const express = require('express')
  4. const cookieParser = require('cookie-parser')
  5. const app = express()
  6. const PORT = process.env.PORT || 8080
  7.  
  8. const whitelist = ['http://192.168.1.17:5173', 'http://localhost:5173']
  9.  
  10. const corsOptions = {
  11.     credentials: true,
  12.     optionSuccessStatus: 200,
  13.     origin: (origin, callback) => {
  14.         console.log('origin is : ', origin)
  15.         if (whitelist.includes(origin)) return callback(null, true)
  16.         callback(new Error('Not allowed by CORS'))
  17.     },
  18. }
  19. app.use(cors())
  20. app.use(cookieParser())
  21.  
  22. app.get('', (req, res) => {
  23.     console.log('req.headers.cookie : ', req.headers.cookie, "and parser's req.cookie is : ", req.cookies)
  24.     res.status(200).send('Request complete')
  25. })
  26. app.listen(PORT, () => console.log('Node alive and listening. Your app is running on port', PORT))
  27.  
  28.  
  29. // CLIENT CODE SNIPPET TO BE PUT INSIDE ANY REACT APP COMPONENT
  30.  
  31. <input
  32.         type={'button'}
  33.         onClick={() => {
  34.             fetch('http://localhost:8080', {
  35.                 mode: 'cors',
  36.                 credentials: 'include',
  37.             })
  38.                 .then((res) => console.log('done', res.status))
  39.                 .catch((err) => console.log('bad', err))
  40.         }}
  41. />
  42.  
Tags: node express
Advertisement
Add Comment
Please, Sign In to add comment