NodeJs 和 Apache 请求的资源上不存在“Access-Control-Allow-Origin”标头

时间:2021-07-26 14:12:36

标签: node.js apache pm2

我已经使用 pm2 和 apache 部署了我的 NodeJs 套接字服务器,并在从我的 angular 应用程序调用时收到错误 No 'Access-Control-Allow-Origin' header is present on the requested resource.。这个问题只有在我使用域名指向的过程中才会出现。使用 http://<ip_address>:<port> 时,它工作正常。

角度代码

setupScheduleSocket(){
  this.scheduleSocket = io.connect(environment.SCHEDULE_SOCKET);
  
  this.scheduleSocket.on('connect', ()=>{
    console.log("connected", environment.SCHEDULE_SOCKET);
  });

  this.scheduleSocket.on('connect_error', () => {
    console.log('connection error');
  });
  this.scheduleSocket.on('disconnect', () => {
    console.log('disconnected');
  });

}

NodeJs

const https = require('http');
//const server = https.createServer();
const socketIO = require('socket.io');

const server = https.createServer((req, res) => {
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
    'Access-Control-Max-Age': 2592000, 
    'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type',
    'Access-Control-Allow-Credentials': true
    
  };

  if (req.method === 'OPTIONS') {
    res.writeHead(204, headers);
    res.end();
    return;
  }

  if (['GET', 'POST'].indexOf(req.method) > -1) {
    res.writeHead(200, headers);
    res.end('Hello World');
    return;
  }

  res.writeHead(405, headers);
  res.end(`${req.method} is not allowed for the request.`);
});


/* socket */

io = socketIO(server);

io.on('connection', (socket) => {
    console.log("connected");

    socket.on('refresh-user', (data)=>{
        io.emit('refresh-user', data);
        console.log(data);
    });

    

});


server.listen(6900, ()=> {
    console.log('listening on 6900');
});

0 个答案:

没有答案