NodeJS “http://127.0.0.1:5500”已被CORS策略阻止

zlhcx6iw  于 2023-01-08  发布在  Node.js
关注(0)|答案(5)|浏览(419)

这是index.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secret</title>
    <script defer src="http://localhost:8000/socket.io/socket.io.js"></script>
    <script defer src="./client/client.js"></script>
    <link rel="stylesheet" href="./css/index.css">
</head>
<body>
    <div class="main">
        <div class="head">this is a chat app</div>
        <div class="container">
            <div class="message right">Lorem ipsum dolor sit qui.</div>
            <div class="message left">Lorem ipsum dolor sit, amet consectetur adipisicin</div>
        </div>
        <div class="send">
            <form action="#" id="send_msg">
                <input type="text" name="messageInput" placeholder="type message😐" id="text">
                <button class="btn" type="submit">send</button>
            </form>
        </div>
    </div>
</body>
</html>

这是client.js代码

const socket=io('http://localhost:8000');

//get dom elements in a js variable;
const form=document.getElementById('send_msg');
const messageInput=document.getElementById("messageInput");
const messageBox=document.getElementsByClassName("container")

const audio=new Audio('ring.mp3')

const append=(message,position)=>{
    const msgElm=document.createElement('div');
    msgElm.innerHTML=message;
    msgElm.classList.add('message');
    msgElm.classList.add(position);
    messageBox.append(msgElm);
    if(position=='left'){
        audio.play()
    }
}

const name=prompt("Enter your name to join");
socket.emit('new-user-joined',name)

socket.emit('user-joined',name=>{
    append(`${name} joined the chat`,'left');
})

socket.emit('receive',name=>{
    append(`${data.name}:${data.message}`,'left');
})

socket.emit('left',name=>{
    append(`${name}: leave the chat`,'left');
})

form.addEventListener('submit',(e)=>{
    e.preventDefault();
    const msg=messageInput.value;
    append(`You: ${message}`,'right');
    socket.emit('send',message);
    messageBox.value="";
});

此 NodeJS 代码

//Node server which will handle socket io connections
const express=require('express');
const app=express();
const io=require('socket.io')(8000);

const cors=require('cors');
app.use(cors({
    origin: "http://127.0.0.1:5500/index.html",
}))

const users={};

io.on('connection',socket=>{
    // if any new user joins,let other users connected to the server know
    socket.on('new-user-joined',name=>{
        console.log(name);
        users[socket.id]=name;
        socket.broadcast.emit('user-joined',name);
    });

    //if someone sends a message,broadcast it to other people
    socket.on('send',message=>{
        socket.broadcast.emit('receive',{message:message,name:users[socket.id]})
    });

    //if someone leaves the chat, let others know
    socket.on('disconnect',message=>{
        socket.broadcast.emit('left',users[socket.id]);
        delete users[socket.id];
    })
})

这里的误差
"CORS策略已阻止从源" http://127.0.0.1:5500 "访问位于" http://localhost:8000/socket.io/?EIO=4&transport=polling&t=Npx4qzO "的XMLHttpRequest:请求的资源上不存在"Access-Control-Allow-Origin"标头。
localhost:8000/socket.io/?EIO=4&transport=polling&t=Npx4qzO:1 Failed to load resource: net::ERR_FAILED
GET http://localhost:8000/socket.io/?EIO=4&transport=polling&t=Npx4x79 net::ERR_FAILED"
图像enter image description here

lrl1mhuk

lrl1mhuk1#

您可以使用单机版运行socket.io。

const { Server } = require("socket.io");

const io = new Server({
    cors: {
        origin: "http://127.0.0.1:5500",
        methods: ["GET", "POST"]
    }
});

io.on("connection", (socket) => {
    // Socket codes...
});

io.listen(8000);
ljo96ir5

ljo96ir52#

试试看:

app.use(cors({
    origin: "http://localhost",
}))

或全部允许,请使用此选项,然后更改它。此选项用于验证\测试。

app.use(cors())
sqougxex

sqougxex3#

尝试此操作此操作更详细,可让您更好地控制CORS配置

// Add a new entry of link that you wish to allow

const allowedOrigins = [
  'capacitor://localhost',
  'ionic://localhost',
  'http://localhost'
];

// Reflect the origin if it's in the allowed list or not defined (cURL, Postman, etc.)

const corsOptions = {
  origin: (origin, callback) => {
    if (allowedOrigins.includes(origin) || !origin) {
      callback(null, true);
    } else {
      callback(new Error('Origin not allowed by CORS'));
    }
  },
};
ajsxfq5m

ajsxfq5m4#

//Node server which will handle socket io connections
const express=require('express');
const app=express();
const io=require('socket.io')(8000);

const cors=require('cors');
app.use(cors({
    origin: "http://127.0.0.1:5500/index.html",
}))

const users={};

io.on('connection',socket=>{
    // if any new user joins,let other users connected to the server know
    socket.on('new-user-joined',name=>{
        console.log(name);
        users[socket.id]=name;
        socket.broadcast.emit('user-joined',name);
    });

    //if someone sends a message,broadcast it to other people
    socket.on('send',message=>{
        socket.broadcast.emit('receive',{message:message,name:users[socket.id]})
    });

    //if someone leaves the chat, let others know
    socket.on('disconnect',message=>{
        socket.broadcast.emit('left',users[socket.id]);
        delete users[socket.id];
    })
})
pw9qyyiw

pw9qyyiw5#

要允许从客户端(即网页)到服务器(即Node.js服务器)的跨源请求,请在服务器端代码中使用此代码片段
const io =新服务器({ cors:{来源:“http://127.0.0.1:5500“,方法:[“GET”,“POST”] } });

相关问题