我目前正在学习如何使用 Node 创建聊天应用程序并为后端表达并为前端做出反应,但遇到 CORS 错误。
由于 CORS,我在下面收到此错误,但是,我已经在应用程序上实现了所有可以实现的 CORS。
这是错误
:3001/chat?name=jaden&room=love:1 Access to XMLHttpRequest at 'http://localhost:8000/socket.io/?EIO=4&transport=polling&t=NOYd8LK' from origin 'http://127.0.0.1:3001' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3001' that is not equal to the supplied origin.
polling-xhr.js:203 GET http://localhost:8000/socket.io/?EIO=4&transport=polling&t=NOYd8LK net::ERR_FAILED
create @ polling-xhr.js:203
Request @ polling-xhr.js:120
request @ polling-xhr.js:63
doPoll @ polling-xhr.js:92
poll @ polling.js:76
doOpen @ polling.js:23
open @ transport.js:43
open @ socket.js:170
Socket @ socket.js:94
push../node_modules/component-emitter/index.js.Emitter.emit @ index.js:145
onError @ polling-xhr.js:246
(anonymous) @ polling-xhr.js:196
setTimeout (async)
xhr.onreadystatechange @ polling-xhr.js:195
:3001/chat?name=jaden&room=love:1 Access to XMLHttpRequest at 'http://localhost:8000/socket.io/?EIO=4&transport=polling&t=NOYd9p5' from origin 'http://127.0.0.1:3001' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3001' that is not equal to the supplied origin.
polling-xhr.js:203 GET http://localhost:8000/socket.io/?EIO=4&transport=polling&t=NOYd9p5 net::ERR_FAILED
这是后端代码
const express = require('express')
const http = require('http')
const socketIo = require('socket.io')
const cors = require('cors')
const app = express()
app.use(cors())
const server = http.createServer(app)
const io = socketIo(server, {
cors: {
origin: "http://localhost:3001",
methods: ["GET", "POST"]
}
})
// Listening for a connection on the socket.io server
io.on('connection', (socket)=>{
// the moment i get a connection, i want to send a welcome message
socket.on('join', ({name, room})=>{
socket.emit('message', {user:'admin', text:`${name}, You're welcome!`})
socket.broadcast.emit('message', {user:'admin', text:`${name}, just joined`})
console.log('welcome message')
})
socket.on('sendMessage', (message)=>{
io.emit('message', {user:'user', text:message})
})
socket.on("disconnect", ()=>{
io.emit('message', {user:'admin', text:`user Just left!`})
})
})
const port = process.env.PORT || 8000
server.listen(port, ()=> console.log(`Listening on port : ${port}`))
本地主机不是实际的来源。源 ip 地址是 127.0.0.1,因此将源从 更改http://localhost:3001
为http://127.0.0.1:3001
。
const io = socketIo(server, {
cors: {
origin: "http://127.0.0.1:3001",
methods: ["GET", "POST"]
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句