错误 WordPress REST API V2 调用与 Vue.js



当我使用 Vue.js 和 axio 调用 WP REST API 时,我收到以下错误。

XMLHttpRequest 无法加载 http://my-wordpress-site.com/wp-json/wp/v2/posts。 "访问控制允许源"标头的值"http://null"不等于提供的源。 因此,不允许访问源"空"。

当我使用带有GET方法的邮递员时,它工作正常。

问题出在哪里?

var app = new Vue({
  el: '#app',
  data: {
    posts: [],
  },
  mounted: function() {
    this.getPosts()
  },
  methods: {
    getPosts: function() {
      var app = this
      axios.get('http://my-wordpress-site.com/wp-json/wp/v2/posts')
      .then(function (response) {
        app.posts = response.data.title.rendered
      })
      .catch(function (error) {
        console.log(error)
      })
    }
  }
});
<div id="app">
  <div class="section">
    <ul>
      <li v-for="post in posts">{{ post }}</li>
    </ul>
    <h3></h3>
  </div>
</div>

我通过在 rest_send_cors_headers() 函数中更改 wp-include/rest-api.php 文件中
的一行来解决它:

header( 'Access-Control-Allow-Origin: *');

最新更新