billchurch / webssh2

Web SSH Client using ssh2, socket.io, xterm.js, and express. webssh webssh2
MIT License
2.36k stars 536 forks source link

CORS origin problem in post request with username and password #332

Closed ErtyDess closed 1 year ago

ErtyDess commented 1 year ago

hello i want from my react app to make a request to webssh2 app passing in post the username and userpassword

i made this code

    async function openSSHremote(sshHost, sshObj) {
      try {
        const response = await fetch(`http://localhost:2224/ssh/host/${sshHost}`, {
          method: 'POST',
          body: JSON.stringify(sshObj),
        });
        const data = await response.json();
        console.log(data);
        console.log('open ssh remote');
        return data;
      } catch (error) {
        console.log(error);
        return error;
      }
    }

here i call it

    function openSshHandler() {
      let sshHost = "192.168.254.102";
      let sshObj = {
        username: props.device.ssh_user,
        userpassword : props.device.ssh_pass
      };
      openSSHremote(sshHost, sshObj);
    }

    <Button variant="contained" style={{ backgroundColor: primary }} onClick={openSshHandler}>open SSH</Button>

react is running on localhost:3000

but i always get cross origin error: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. even if i put the origin in the webssh2 config.json.

config.json

    "socketio": {
      "serveClient": false,
      "path": "/ssh/socket.io",
      "origins": ["localhost:3000"]
    },
ErtyDess commented 1 year ago

i solved it adding

  app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
  });

to the server app.js