Goal: Connect vue.js to Wagtail-API/pages.
I have configured the wagtail API v2 as per the setup guide, however, the Vue-resource get request is not working out.
Console Error:
Failed to load http://localhost:8000/api/v2/pages/: Response to preflight
request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Searching the error leads me to believe that I should implement CORS. However, I have seen a few Django_rest + Vue.js tutorials and none have mentioned CORS. Is it truly necessary to implement CORS? Also, should I use Axios rather than vue-resource?
Relevant vue.js and wagtail-API code below:
The following HTML is based on this tutorial. The current pages print, but the ones I am requesting do not.
HTML/Django_template:
{% extends "base.html" %}
{% load static wagtailcore_tags %}
{% block content %}
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.0"></script>
<div id="test">
<ul>
<li v-for="print_test in pages">
<p> [[print_test]]</p>
</li>
</ul>
</div>
<script type="text/javascript">
var app=new Vue({
el: "#test",
delimiters: ['[[', ']]'],
data: function(){
return {
search: '',
pages: [
{ id: '1', title: 'one'},
{ id: '2', title: 'two'},
{ id: '3', title: 'three'}
]};
},
http: {
root: 'http://localhost:8000',
headers: {
Authorization: 'CAUSING ERROR...'
}
},
methods: {
getPages: function () {
this.$http.get('api/v2/pages/?type=blog.blogpage').then(function (data,status,request)
{
if (status == 200) {
this.pages = data;
console.log(data);
}
})
}
},
mounted: function () {
this.getPages();
}
});
</script>
{% endblock %}
The following covers my API setup– provided in case I missed something.
settings/base.py:
INSTALLED_APPS = [
'rest_framework',
'wagtail.api.v2',
]
api.py:
from wagtail.api.v2.endpoints import PagesAPIEndpoint
from wagtail.api.v2.router import WagtailAPIRouter
from wagtail.wagtailimages.api.v2.endpoints import ImagesAPIEndpoint
from wagtail.wagtaildocs.api.v2.endpoints import DocumentsAPIEndpoint
api_router = WagtailAPIRouter('wagtailapi')
api_router.register_endpoint('pages', PagesAPIEndpoint)
api_router.register_endpoint('images', ImagesAPIEndpoint)
api_router.register_endpoint('documents', DocumentsAPIEndpoint)
urls.py:
from .api import api_router
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls')),
url(r'^api/v2/', api_router.urls),
url(r'', include(wagtail_urls)),
]
blog/model.py:
from django.db import models
from django.http import HttpResponse
from wagtail.api import APIField
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
categories = ParentalManyToManyField('blog.BlogCategory', blank=True)