# 跨域测试



## 后端

```shell
npm install # 安装依赖后
npm run dev # 启动依赖
接下来我们可以访问 localhost:8086/get?id=2 来进行请求测试
```



## 前端

```shell
# 前端就是在根目录下面的helloworld.html
这里我script 里面写入一个 向着 /api 发起的请求
```



## 跨域配置

### window

```js
C:\Windows\System32\drivers\etc\hosts 中加入
127.0.0.1       你的后端地址
```

### nginx

```shell
# start.bat 移入里面
nginx.conf 中加入


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       5501;
        server_name  a.b.com;

        #charset koi8-r;

        # access_log  logs/host.access.log  ;

   

         location /api {
            add_header 'Access-Control-Allow-Origin' *;
            #允许带上cookie请求
            add_header 'Access-Control-Allow-Credentials' 'true';
            #允许请求的方法，比如 GET/POST/PUT/DELETE
            add_header 'Access-Control-Allow-Methods' *;
            #允许请求的header
            add_header 'Access-Control-Allow-Headers' *;
            # error_page 405 =200 http://$host$request_uri;
            #后端 的 地址
            proxy_pass http://localhost:8086;
            proxy_redirect off;
            proxy_set_header Host $host;
			proxy_set_header X-Forwarded-Proto $scheme;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header Upgrade $http_upgrade; 
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_connect_timeout 18000;
			proxy_send_timeout 18000;
			proxy_read_timeout 18000;
            # index  index.html index.htm index.jsp;
            
        }
    }


}


```



## 最后

最后把打包后的文件放在nginx/html 这样子就可以请求成功了

```js
里面的文件这样请求

 let ajax = (data, url) => {
     //step1 : 设置请求头
     let xhr = new XMLHttpRequest();
     //step2：设置请求方式和请求头 //true表示异步
     xhr.open("get", url, true);
     xhr.setRequestHeader("Content-type", "application/json");
     //step3：请求数据
     xhr.send();
     // step4：readyState是xhr的请求状态
     //状态4表示已发送请求，服务器已完成返回响应，浏览器已完成了下载响应内容。0-4都有值的
     xhr.onreadystatechange = function () {
         if (xhr.readyState === 4 && xhr.status === 200) {
             console.log(xhr.responseText);
         }
     };
 }
 let url = "/api/get?idcxzdddd"

 ajax(url, url)


最后访问类似于
http://a.b.com:5501/
```







## 缺点：

dev环境下面似乎会非常麻烦



