V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zzl
V2EX  ›  V2EX

为啥我请求 V2EX 提供的 API 报跨域了,你们也这样吗?

  •  
  •   zzl · 2018-03-16 17:46:42 +08:00 · 4336 次点击
    这是一个创建于 2204 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Failed to load https://www.v2ex.com/api/topics/hot.json: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405.
    12 条回复    2018-03-21 14:44:35 +08:00
    airyland
        1
    airyland  
       2018-03-16 17:55:57 +08:00
    先 google 下相关知识,V2EX 并没有设置(也不可能)规则为 * 的 cors 规则,也没有提供 jsonp 接口,所以跨域错误是正常的。接口使用后端语言访问吧或者做一层代理。
    MaiCong
        2
    MaiCong  
       2018-03-16 17:58:14 +08:00
    浏览器端直接访问是会出现跨域提示的,这种时候就得使用后端的骚操作了
    daishankeke
        3
    daishankeke  
       2018-03-16 18:00:50 +08:00
    1L 说得对
    xiaoz
        4
    xiaoz  
       2018-03-16 23:41:23 +08:00 via Android
    建议用 curl 来请求接口,就不会出现跨域问题。
    xiaoz
        5
    xiaoz  
       2018-03-16 23:42:02 +08:00 via Android
    49gd
        6
    49gd  
       2018-03-17 09:54:23 +08:00
    反代 在访问不就好了
    zzl
        7
    zzl  
    OP
       2018-03-17 11:57:38 +08:00 via Android
    @airyland 好吧,其实我在学 react,想仿个 v 站,用 axios 请求 v 站的 api 接口,结果就这样
    zzl
        8
    zzl  
    OP
       2018-03-17 12:00:14 +08:00 via Android
    @MaiCong 用 chrome 打开不会报错,本地用 axios 请求就报错了,不知道是哪里的设置问题,还是只能用后端来操作。同样的代码,使用 cnode 的公共 api 就没有问题
    zzl
        9
    zzl  
    OP
       2018-03-17 12:01:42 +08:00 via Android
    @49gd 只想用 react 仿一下 v 站,用 axios 发的请求,不想写后端,只能加个代理吗
    HowardTang
        10
    HowardTang  
       2018-03-17 12:29:10 +08:00
    nginx 反代一下..很简单的
    xiongshengyao
        11
    xiongshengyao  
       2018-03-21 14:43:42 +08:00
    nginx 做一下反向代理,恰好我以前写写过类似的,直接给你把 nginx 配置贴出来吧
    ```
    server {
    listen 8082;

    root /home/xsy/react-v2ex/dist;
    index index.html;

    location /api {
    proxy_set_header Host www.v2ex.com;
    proxy_pass https://www.v2ex.com;
    proxy_buffers 16 4k;
    }

    location / {
    try_files $uri $uri/ /index.html;
    }
    }
    ```
    xiongshengyao
        12
    xiongshengyao  
       2018-03-21 14:44:35 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4034 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:18 · PVG 18:18 · LAX 03:18 · JFK 06:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.