前端获取8080端口服务的数据localhost:3000' is therefore not allowed access.

蓝with黑
  • 481

node.js前端运行在localhost:3000,
通过ajax获取运行在8080端口的java服务返回的数据报了这个错误:
(local:8080/wechat/api/alarms/1)

XMLHttpRequest cannot load http://localhost:8080/wechat/api/alarms/1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

js---------------------------------------------------------------------
var alarmUrl='http://localhost:8080/wechat/api/alarms';
mui.ajax({

                    url:alarmUrl+'/'+page,
                    type:'GET',
                    dataType:'json',
                    success:function(data){
                        console.log(data);
                    },
                    error:function(xhr,type,errorThrown){
                        //打印报错
                        console.log(xhr+'\n'+type+'\n'+errorThrown);
                    }
                    
                    

java-------------------------------------------------------------------
通过RESTful API接口对外提供数据

接口uri:
/wechat/api/alarms/{page}

node--app.js代码-----------------------------------------------------------
var express=require('express');
var app=express();
var path=require('path');
var logger = require('morgan');//logger(记录器),在控制台中,显示req请求的信息。
var http=require('http')
//bodyParser用于解析客户端请求的body中的内容,内部使用JSON编码处理,url编码处理以及对于文件的上传处理.
var bodyParser=require('body-parser');
var favicon=require('serve-favicon');
var cookieParser=require('cookie-parser');
var session=require('express-session');

var news_main=require('./routes/news_main');
var pullrefresh_sub=require('./routes/pullrefresh_sub');
var boiler_alarm=require('./routes/boiler_alarm')
var login=require('./routes/login');

app.use(session({

secret:'a~Kf?)P{3490*&(',//密码字符串
maxAge:3600000,//定制session的会话时长
resave:true,//是否每次都保存
saveUninitialized:true

}));

//var news_page=require('./routes/news_page');
// app.get('/',function(req,res){
// res.render('news_main');
// });

// 定义模板
app.set('views',path.join(__dirname,'views'));
app.engine('html',require('ejs').renderFile);
app.set('view engine','html');
//静态文件目录,
app.use(express.static(path.join(__dirname,'public')));

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({

extended:false

}));

app.use(cookieParser());

/**
*路由配置
*/
app.use('/',news_main);
app.use('/pull',pullrefresh_sub);
app.use('/alarm',boiler_alarm);
app.use('/',login);

var server=app.listen(3000,function(){

var host=server.address().address;
var port=server.address().port;
console.log("Example boiler listing at http://%s:%s",host,port);

});

node---boiler_alarm.js(路由部分代码) -------------------------------------------------------

var express=require('express');
var router=express.Router();
router.get('/',function(req,res,next){

res.render('boiler_alarm',{
    title:'报警模块'
});

});

这里网上看到加这个,但是没用
//router.use(function (req, res, next) {
//res.header("Access-Control-Allow-Origin", "*");
//res.header("Access-Control-Allow-Headers", "X-Requested-With");
//res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//next();
//});

module.exports=router;

回复
阅读 6.2k
3 个回答

nodejs 解除跨域限制:

app.all('*', function(req, res, next) {

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();

});

你是在做开发吧,我一开始也遇到这个问题,很头疼,配置了好久也确实搞好了,但是后来都被删掉了,因为其实没什么用。

看起来你发送ajax请求用的是jquery,你或许可以搜搜jquery跨域要不要做一些特殊设置。反正服务器端和客户端都要设置好了才行。

但是你有一个很简单的办法绕过这个限制,就是用nginx做一下反向代理,你看我的nginx配置

    upstream webpack {
        server 127.0.0.1:8080;
        keepalive 64;
    }
    
    upstream nodejs {
        server 127.0.0.1:3000;
        keepalive 64;
    }

    server {
        listen       80;
        server_name  localhost;

        location / {
            client_max_body_size 10m;
            proxy_pass http://nodejs;
        }
        
        location /js/ {
            proxy_pass  http://webpack;
        }

只需要给两个upstream分配不同的url,就可以统一使用localhost来访问,而不用用端口号来访问了,这样子就可以避免去配置跨域这种麻烦的事情

你知道吗?

宣传栏