因为react项目前后端分离,本地打包发布之后,出现了跨域问题,因此用到了nginx解决这个跨域的“大”问题。
研究了一个上午,只能说是懂了一些参数,但是对于应用到项目中解决跨域貌似差着一个时空的距离。
最终我搞懂的几个问题:
1、nginx是个啥?
2、咋用啊?
3、我需要做啥?
4、谁能告诉我?
答案就是先照着下边做,也是很容易在网上找到的资料
具体解决如下:
1、下载nginx (windows版本):
下载地址:http://nginx.org/en/download.html 选一个下载即可
解压
文件如下:
2、 安装:
方法一: 可以双击ngnix.exe文件
会看到一个一闪而过的黑框,说明执行了,然后浏览器访问http://localhost:80 试试
方法二: 命令行的方式 (推荐)
在nginx.exe所在目录运行cmd,然后输入start nginx
3、启动:
默认访问http://localhost:80
(注:这里我想说一下,由此启动可以知道,nginx就是一个功能如同iis的可以访问网页的一种工具,直接配置你要访问的地址就可以了,当时我还傻傻的不知道是什么鬼)
4、配置
配置文件是这个
打开看一下:
#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 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
不知道都是什么鬼,简单说明
1、#代表注释 ,就是后边的代码都没有执行
2、重点配置的代码块在
http {.....
server{
这个部分。
3、上我修改的代码吧,送给想知道结果的你,其他的语言都是多余的,先实现了再说。
listen 8011; #我的站点的端口号
server_name 56.155.54.27; #我本地的地址
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root D:\Practice\PackDemo\build; #项目的路径
index index.html index.htm; #项目的启动页
try_files $uri /index.html; #对单页程序做的回跳
}
location /api/ { #请求的路径
proxy_pass http://56.155.54.144:8091/; #请求的地址
}
意会吧,懒得写了,项目里,把请求的地址写成 56.155.54.27:811/api 即可
愿你尽快调通你的代码,欢迎留言!