今天完成的事情:
在angularJS中用解决跨域问题:
以nginx为栗子:
server {
server_name www.minguang.xyz; # 虚拟主机域名
location /api/ {
proxy_pass http://dev.admin.carrots.ptteng.com/; # 写上要转发到的地址,可以是http也可以是https,注意不要遗漏了最后的斜杠
proxy_pass_header Set-Cookie; # 带cookie转发
proxy_set_header Host dev.admin.carrots.ptteng.com; # 转发的时候模拟成对方的主机
}
}
这里使用一个grunt的插件 :grunt-connect-proxy
安装:npm install grunt-connect-proxy --save-dev
添加proxy任务:
在Gruntfile.js中的grunt.initConfig之前,插入一句:
grunt.loadNpmTasks('grunt-connect-proxy');
配置proxy
在grunt.initConfig中的connect配置项下,插入一个子项:
proxies: [
{
context: '/api', // 这是你希望出现在grunt serve服务中的路径,比如这里配置的是http://127.0.0.1:9000/api/
host: 'www.ngnice.com', // 这是你希望转发到的远端服务器
port: 80, // 远端服务器端口
changeOrigin: true, // 建议配置为true,这样它转发时就会把host带过去,比如www.ngnice.com,如果远端服务器使用了虚拟主机的方式配置,该选项通常是必须的。
rewrite: {
'^/api/': '/remote_api/' // 地址映射策略,从context开始算,把前后地址做正则替换,如果远端路径和context相同则不用配置。
}
}
],
配置middleware:
在grunt.initConfig.connect.livereload.options配置项下,插入一个子项(摘自官方例子):
middleware: function (connect, options) {
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
// 设置代理
var middlewares = [require('grunt-connect-proxy/lib/utils').proxyRequest];
// 代理每个base目录中的静态文件
options.base.forEach(function(base) {
middlewares.push(connect.static(base));
});
// 让目录可被浏览(即:允许枚举文件)
var directory = options.directory || options.base[options.base.length - 1];
middlewares.push(connect.directory(directory));
return middlewares;
}
启动proxy:
grunt.registerTask('serve', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'bowerInstall',
'concurrent:server',
'autoprefixer',
'configureProxies:server', // *** 务必插入这句 ***
'connect:livereload',
'watch'
]);
});
在grunt serve运行的同时就会也把这个proxy插件加载了。这个插件如果正常启动,会在控制台看到下列信息:
Running "configureProxies:server" (configureProxies) task
Rewrite rule created for: [/^/api// -> /remote_api/].
Proxy created for: /api to www.ngnice.com:80
明天计划的事情:
继续做任务
问题:
调试API有没有更加简便的方法
收获:
如上
评论