node.js – 如何在所有文件上的express.js 4.x上启用CORS?

我继续收到

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
07000.
(Reason: CORS request Failed).

而我尝试访问我的node.js.这对我来说不行:

app.use(function(req,res,next) {
  res.header("Access-Control-Allow-Origin","*");
  res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");
  next();
});

@edit:这是更新完整的代码

var express = require('express');
var http = require('http');
var expressvar = express();

expressvar.use(function (req,next) {
    res.setHeader('Access-Control-Allow-Headers','accept,authorization,content-type,x-requested-with');
    res.setHeader('Access-Control-Allow-Methods','GET,HEAD,PUT,PATCH,POST,DELETE');
    res.setHeader('Access-Control-Allow-Origin',req.header('origin'));
    next();
});
expressvar.use(express.static('../'));
expressvar.use("/socket.io",express.static('../socket.io'));
var app = http.createServer(expressvar);
var io = require('socket.io').listen(app);
app.listen(2013);

解决方法

尝试这个解决方案(编辑包括完整的工作代码)

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

io.set('origins','*:*');

app.use(function(req,next) {
  res.header('Access-Control-Allow-Origin',req.get('Origin') || '*');
  res.header('Access-Control-Allow-Credentials','true');
  res.header('Access-Control-Allow-Methods',DELETE');
  res.header('Access-Control-Expose-Headers','Content-Length');
  res.header('Access-Control-Allow-Headers','Accept,Authorization,Range');
  if (req.method === 'OPTIONS') {
    return res.send(200);
  } else {
    return next();
  }
});

server.listen(80);

app.get('/',function (req,res) {
  res.send('OK');
});

io.on('connection',function (socket) {
  socket.emit('news',{ hello: 'world' });
  socket.on('my other event',function (data) {
    console.log(data);
  });
});

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...