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;
nodejs lifts cross-domain restrictions:
app.all('*', function(req, res, next) {
});
Are you doing development? I also encountered this problem at the beginning. It was a headache. After a long time of configuring it, I got it right, but later it was deleted because it was of no use.
It seems that you are using jquery to send ajax requests. You may be able to search whether you need to make some special settings for jquery cross-domain. Anyway, both the server and the client must be set up.
But you have a very simple way to bypass this restriction, which is to use nginx as a reverse proxy. Look at my nginx configuration
You only need to assign different URLs to the two upstreams, and you can use localhost to access them instead of using port numbers. This way you can avoid the trouble of configuring cross-domain configurations
Reference http://www.ruanyifeng.com/blog/2016/04/cors.html