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;
巴扎黑2017-04-18 09:28:09
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();
});
阿神2017-04-18 09:28:09
你在做開發吧,我一開始也遇到這個問題,很頭疼,配置了好久也確實搞好了,但是後來都被刪掉了,因為其實沒什麼用。
看起來你發送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來訪問,而不用用端口號來訪問了,這樣子就可以避免去配置跨域這種麻煩的事情