【问题标题】:Cors Issue when accessing steam API Vue Axios [duplicate]访问 Steam API Vue Axios 时出现 Cors 问题 [重复]
【发布时间】:2018-09-30 13:55:00
【问题描述】:

我是 Vue 的新手,但我试图从 csgo 周围的 Steam api 中获取一些细节。当我尝试引入数据时,它会在 api url 上出现 405 (Method Not Allowed) 并且 对预检请求的响应未通过访问控制检查:No 'Access -Control-Allow-Origin' 标头存在于请求的资源上。因此,Origin 'http://127.0.0.1:8000' 不允许访问。响应的 HTTP 状态代码为 405。

我似乎无法解决这个问题,我尝试使用一些在线代理并将 URL 放在 Steam api 之前,但没有运气。

任何帮助将不胜感激!谢谢!

<template>
        <div>
            <ul v-if="posts && posts.length">
                <li v-for="post of posts">
                    <p><strong>{{post.steamID}}</strong></p>
                    <p>{{post.stats}}</p>
                </li>
            </ul>

            <ul v-if="errors && errors.length">
                <li v-for="error of errors">
                    {{error.message}}
                </li>
            </ul>
        </div>
</template>

<script>
    import axios from 'axios';

    export default {
        data() {
            return {
                posts: [],
                errors: []
            }
        },

        // Fetches posts when the component is created.
        created() {
            axios.get(`http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=52828DE98A6C45A556BF4E5AF4F3CF1D&steamid=76561197980619010`)
                .then(response => {
                    // JSON responses are automatically parsed.
                    this.posts = response.data
                })
                .catch(e => {
                    this.errors.push(e)
                })

            // async / await version (created() becomes async created())
            //
            // try {
            //   const response = await axios.get(`http://jsonplaceholder.typicode.com/posts`)
            //   this.posts = response.data
            // } catch (e) {
            //   this.errors.push(e)
            // }
        }
    }
</script>

【问题讨论】:

  • 看来api.steampowered.com不是你自己的服务器,你不能更改CORS的配置。因此您可能必须构建一个反向代理或将您的请求发送到您的后端服务器,然后让后端调用该 URL。

标签: javascript api vue.js cors


【解决方案1】:

这是您的网络浏览器和网络服务器的一部分。

它基本上可以阻止恶意攻击,例如

  1. 您访问my-innocent-blog.com,它有一个“喜欢我的网站”按钮
  2. 您点击它,它会向 StackOverflow 发送删除您帐户的请求。
  3. StackOverflow 服务器收到 DELETE 请求,其来源是 my-innocent-blog.com,它会告诉您的网络浏览器“该请求只能来自我们自己的网站”。
  4. 您的网络浏览器显示“好的,我将忽略该请求并引发 CORS 错误”

从而保护您免于意外被欺骗删除您的帐户(或更糟)。

如果您使用的是 ExpressJS 服务器,请查看他们的 CORS 包。 https://github.com/expressjs/cors

否则,只需在 Google 上搜索“CORS”,您就会发现几乎所有内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-08
    • 2020-01-02
    • 2020-05-14
    • 2020-11-08
    • 2019-08-29
    • 2020-03-05
    • 2021-03-15
    • 1970-01-01
    相关资源
    最近更新 更多