Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

node.js - Can`t set headers in socket.io using node js and react

the socket work well but I get undefined when I try console.log my header, I can see the headers but not the header that I try to send. (try to send jwt to backend and check validity before connection)

there is my backend:

 const express = require("express");
    const cors = require("cors");
    const app = express();
    const mongoose = require("mongoose");
    const bodyParser = require("body-parser");
    const initListeners = require("./socket");
    const socketio = require('socket.io');
    const http = require('http')
    const seeds = require('./seeds');
    
    const server = http.createServer(app);
    const io = socketio(server);
    require("dotenv").config();
    
    app.use(cors({ 
      credentials: true, 
      origin: 'http://localhost:3000',
    }));
    
    initListeners(io);
    
    
    io.on("connection", function (socket) {
        let token = socket.handshake.headers['x-clientid'];
        console.log(token);
        console.log('user connected!');
    })

client:

 let socket;
    const SideBar = (props) => {
        useEffect(() => {
            socket = io( 'http://localhost:5000', {
                transports: ['websocket', 'polling', 'flashsocket'],
                transportOptions: {
                  polling: {
                    extraHeaders: {
                      'x-clientid': 'abc'
                    }
                  }
                }
              });
        }, [])
        return(
            <div className={classes.SideBar}>
                
            </div>
        )
    }

export default SideBar;
question from:https://stackoverflow.com/questions/65904857/cant-set-headers-in-socket-io-using-node-js-and-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...