与ec2 aws服务器的HTTP请求不工作



我在AWS上有一个EC2实例,我已经部署了一个MERN堆栈,我已经定义了nginx如下:

server {
#listen       80;
listen 80 default_server;
listen [::]:80 default_server;
server_name  yourdomain.com;
access_log /home/ubuntu/client/server_logs/host.access.log main;
client_max_body_size 10M;
location /api/ {
add_header X-debug-message innnnnnnnnnnnnn;
proxy_pass http://localhost:3000/;
}
location /admin-dashboard {
root /home/ubuntu;
index index.html;
add_header X-uri "$uri";
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";
} 
location / {
root /home/ubuntu/client/deploy;
index index.html index.htm;
try_files $uri $uri/ /index.html;
add_header X-uri "$uri";
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";
}



location = /49x.html {
root   /usr/share/nginx/html;
}
server_tokens off;
location ~ /.ht {
deny  all;
}
}

我附上了安全组作为截图。当我试图用这个url http://clikjo.com/api/获取数据时,使用浏览器或邮差它工作得很好,但是当我尝试使用javascript与fetch或Axios一起使用时,它会出现此错误:[TypeError: Network request failed]

谁能解决我的问题?i have try to:

  • 更改我的安全组
  • 添加标题,指定模式,获取选项,…等

如果您在浏览器中使用HTTPS加载页面,浏览器将拒绝通过HTTP加载任何资源。正如您所尝试的,将API URL更改为使用HTTPS而不是HTTP通常可以解决此问题。但是,您的API必须不允许HTTPS连接。因此,您必须在主页上强制使用HTTP,或者请求他们允许HTTPS连接。

请注意:如果您转到API URL而不是尝试用AJAX加载它,请求仍然可以工作。这是因为浏览器没有从安全页面中加载资源,而是加载了一个不安全的页面,并接受了这个页面。但是,为了使它可以通过AJAX使用,协议应该匹配。

您正在获得CORS错误。你需要在服务器端用附加的头来修复它。

add_header Access-Control-Allow-Origin *;