跨域说通俗点就是在A网中使用ajax去获取B网站的特定内容,这个就是跨域。跨域有两种形式,一种是同一ip不同端口的跨域,一种是不同ip的跨域。
现在说说项目中用到的解决跨域文件上传的方法,中间遇到的各种坑就不说了;该上传方法适用上述两种情形。
注意该架构用的是nginx作为web服务器。
前端html
<form id="fp" action="" method="post" enctype="multipart/form-data">
<table >
<tr>
<td width="100" align="left"><input type="file" name="file" id="file" /></td>
<td width="100" align="left"><input id="sub" style="background-color:#669900;" οnclick="ajaxUp()" type="button" name="submit" value="上传" />
</tr>
</table>
</form>
//ajax
function ajaxUp(){
var formElement = document.forms.namedItem("fp");
var xhr = new XMLHttpRequest();
xhr.open("POST", upHttp, true);
xhr.send(new FormData(formElement));
xhr.onload = function(e){
var messg = eval('(' + this.response + ')');
cookies(messg.id);
location.reload();
}
}
nginx配置
#user www www;
worker_processes 1; #启动进程,通常设置成和cpu的数量相等
worker_rlimit_nofile 204800;
events
{
use epoll; #epoll是多路复用IO(I/O Multiplexing)中的一种方式,但是仅用于linux2.6以上内核,可以大大提高nginx的性能
worker_connections 100; #单个后台worker process进程的最大并发链接数
}
http
{
access_log /opt/v0.1/wordFreServer/ngx_openresty/logs/access_appname.log combined;
error_log /opt/v0.1/wordFreServer/ngx_openresty/logs/error_appname.log crit;
include mime.types; #设定mime类型,类型由mime.type文件定义
default_type application/octet-stream;
#sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,
#必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 60; #连接超时时间
client_header_buffer_size 2k; #设定请求缓冲
lua_shared_dict config 1m;
#init_by_lua_file 'server/init.lua';
server{
listen 8000;
server_name localhost;
location ~* /(\w+)/static/ {
root /opt/v0.1/wordFreServer/ngx_openresty/web2py/applications/;
}
location / {
uwsgi_pass 127.0.0.1:9001;
include uwsgi_params;
}
}
server
{
listen 7777; #侦听端口
server_name localhost;
lua_code_cache on; #上线后请设置为on
client_max_body_size 512m;
location /favicon.ico { log_not_found off; access_log off; }
location /wordFreq/upFile {
if ($request_method = 'POST'){
add_header 'Access-Control-Allow-Origin' '*';
#set $debug "on";
content_by_lua_file server/upFile.lua;
}
}
location /wordFreq/act {add_header 'Access-Control-Allow-Origin' '*'; set $debug "on"; content_by_lua_file server/act.lua; }
location /test { default_type text/html; content_by_lua 'ngx.say("hello world")';}
location ~* ^(.+\.txt)$ {
add_header 'Access-Control-Allow-Origin' '*';
root /opt/v0.1/wordFreServer/result;
access_log off;
expires 30d;
add_header Content-Disposition "attachment; filename=$1";
}
}
在服务端的为某个请求服务添加 add_header 'Access-Control-Allow-Origin' '*'; 就能实现跨越,并且能够获得response,也不会出现警告信息。