Saturday 3 June 2017

express.js The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'

I'm trying to make an auth with sending token via cookies and Authorization header to ensure that username from header and username from decoded token are identical. But the problem is, when I send authorization header, on backend OPTIONS request fails with 204 error. Without header it works perfectly. What I've tried: Added middleware for handling this, OPTIONS still 204.

app.use((req, res, next) => {
  console.log(`headers`)
  console.log(req.headers)
  res.header("Access-Control-Allow-Credentials", "true")
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "X-Requested-With")
  res.header("Access-Control-Allow-Headers", "Content-Type")
  res.header("Access-Control-Allow-Headers", "Authorization")
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS")
  if ('OPTIONS' == req.method) {
    res.send(200)
  }
  else {
    next();
  }
}) 

  1. Set up cors

app.use(cors({withCredentials: true, credentials: true, origins: 'http://localhost:8080'}))

  1. Set up socket.io

    var socket = require('socket.io')
    var app = express(),
    var http = require('http').createServer(app)
    const io = new socket(http, { path: '/api/chat', origins: 'http://localhost:8080' })
    http.listen(3000, () => console.log(`App is running on localhost:3000`.bold.yellow))
    const events = require('./src/socket')(io); 
    
    

But it still doesnt work. What could have I missed?



via zaebalo

No comments:

Post a Comment