0

Access to XMLHttpRequest at 'http://localhost:3030/socket.io/?EIO=3&transport=polling&t=NHnZ9gy' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

============================== node socket code

import socketIO from 'socket.io';
import jwt from 'jsonwebtoken';
import { get } from 'lodash';

async function authMiddleware(app, socket, next) {
  try {
    const token = get(socket.request.headers, 'authorization', null);
    if (!token) {
      return next(new Error('Invalid authentication token'));
    }

    // Validate access token
    const appSecret = app.get('config').appSecret;

    // Invalid authorization header
    const tokenValues = token.split(' ');
    if (tokenValues.length !== 2) { throw new Error('Invalid token'); }
    if (tokenValues[0] !== appSecret.tokenType) { throw new Error('Invalid token'); }

    // Decode token and inject user data in request
    const payload = await jwt.verify(tokenValues[1], appSecret.key);

    // Find user
    const User = app.get('models').user;
    const userQuery = { where: { id: payload.id } };
    const user = await User.findOne(userQuery);
    
    if (!user) { throw new Error('No user found'); }

    // Set user instance to socket
    socket.user = user;
    return next();
  } catch (err) {
    return next(err);
  }
}

export default function (app) {
  const io = socketIO(app.server, {
    handlePreflightRequest(req, res) {
      const headers = {
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
        'Access-Control-Allow-Origin': req.headers.origin,
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS'
        //'Access-Control-Allow-Origin': '*://*'
      };
      res.writeHead(200, headers);
      res.end();
    }
  });
  // const io = socketIO(app.server);
  //io.origins('*:*')
  io.use((socket, next) => authMiddleware(app, socket, next));
  console.log("Socket call");
  io.on('connection', socket => {
    // On connect, join the socket to user room
    const user = socket.user;
    if(user.type == 'Processor'){
      socket.join("Processor-"+user.companyId);
    } else if(user.type == 'Admin'){
      socket.join("Processor-"+user.companyId);
    }  
    else{
      socket.join("Customer-");
    }
    console.log(socket.id,"Joins",user.type+"-"+user.companyId);
    if (user) {
      socket.on(`syncDriverLocation-${user.id}`, payload => {
        const { tripId, isDbUpdate, latitude, longitude } = payload;
        socket.broadcast.emit(`syncDriverToTrip-${tripId}`, payload);
       // if (isDbUpdate) {
          const driverLocation = {
            type: 'Point',
            coordinates: [longitude, latitude]
          };
          console.log('driverLocation',driverLocation)
          const Trip = app.get('models').trip;
          Trip.findOne({ where: { id: tripId }}).then((trip) => {
            trip.update({ driverLocation }).then();
          });
          console.log('Trip',Trip)
          const TripLocation = app.get('models').tripLocation;
          TripLocation.create({
            tripId,
            driverLocation: {
              type: 'Point',
              coordinates: [longitude, latitude]
            },
          }).then();
       // }
      });
    }
  });

  app.set('io', io);
}

=================================== this is my initialize code in react

this.socket = io('http://localhost:3030'
    , {
      reconnect: true,
      transportOptions: {
        polling: { extraHeaders: { 
         authorization: getAccessHeader() 
        } }
      }
    }
    );
    this.socket.on("connect", () => {
      console.log(`===============Socket Connected(${this.socket.id})===============`);
    }).on("error",(err) => {
      console.log(
        `===============Socket error===============`,err
      );
    })

    this.socket.on("disconnect", () => {
      console.log(`===============Socket Disconnected===============`);
    });
  • Does this answer your question? [Socket.io + Node.js Cross-Origin Request Blocked](https://stackoverflow.com/questions/24058157/socket-io-node-js-cross-origin-request-blocked) – OfirD Sep 09 '20 at 11:03
  • I also did this but no effect on my code – Swarnabha Paul Sep 09 '20 at 12:59

0 Answers0