So beheben Sie den CORS-Fehler in Socket IO NodeJS

[ad_1]

So beheben Sie den CORS-Fehler in Socket IO NodeJS

In diesem kurzen Tutorial zeige ich Ihnen, wie Sie CORS-Fehler im Socket-IO in NodeJS beheben können.

Zunächst müssen Sie die Socket-IO-Importanweisung wie folgt verwenden:

const socketIO = require("socket.io")(http, {
	cors: {
		origin: "*"
	}
})

Anschließend können Sie mit Ihrer Express-App-Instanz die folgenden Header festlegen.

// Add headers before the routes are defined
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader("Access-Control-Allow-Origin", "*")

    // Request methods you wish to allow
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE")

    // Request headers you wish to allow
    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,Authorization")

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader("Access-Control-Allow-Credentials", true)

    // Pass to next layer of middleware
    next()
})


[ad_2]