Vuejs axios error when making post request - http

I'm new to vuejs and i'm following this tutorial
(https://www.youtube.com/watch?v=Wy9q22isx3U&t=3492s).
When i tried to make a post request i got this error (has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.)
I could console.log(res.data) but i couldn't put it inside todos[] array.
addtodo(newTodo){
const {title,completed} = newTodo;
axios.post('https://jsonplaceholder.typicode.com/todos',{
title,
completed
})
.then(res => {
this.todos = this.todos.push[res.data];
//console.log(res.data);
})
.catch(err => console.log(err));
}

you are using .push() wrong, it is parenthesis not bracket.
new Vue({
el: "#app",
data: {
todos:[{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}]
},
methods: {
addtodo(newTodo){
const {title,completed} = newTodo;
axios.post('https://jsonplaceholder.typicode.com/todos',{
title,
completed
})
.then(res => {
this.todos.push(res.data);
console.log(res.data);
})
.catch(err => console.log(err));
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button #click="addtodo({title:'New todo',completed:true})">
click to add todo
</button>
<ul>
<li v-for="todo in todos" :key="todo.id">{{todo.title}}</li>
</ul>
</div>

no need to this.todos = this.todos.push() just use
this.todos.push(res.data)

Related

Why my async fetch doesn't work client side?

I'm having an issue to get my component working client side with fetch (it's ok when I'm refreshing the page) in Nuxt.
The $fetchState.error doesn't load any error though. But my console.log in my mounted hook doesn't load any data.
I don't know what I'm doing wrong here. I'm using target: 'static'
<template>
<p v-if="$fetchState.pending">Fetching realisation...</p>
<p v-else-if="$fetchState.error">An error occurred :(</p>
<nuxt-link v-else :to="real.full_slug" class="real">
<div class="real__content">
<h2>{{ real.name }}</h2>
</div>
</nuxt-link>
</template>
<script>
export default {
props: {
realisation: {
type: Object,
required: true
}
},
data() {
return {
real: {}
}
},
async fetch() {
this.real = await this.$storyapi
.get(`cdn/stories/${this.realisation.work}`, {
version: 'published',
find_by: 'uuid'
})
.then((res) => {
return res.data.story
})
.catch((err) => console.log(err))
},
mounted() {
console.log(this.real)
},
fetchOnServer: true
}
</script>

How do I display a route parameter (Vue / Firebase)

I'm creating a blog with free sewing patterns as content. I'm using route parameters to receive each blog individually. However, I'm getting a blank page when trying to retrieve its data from firebase firestore. Please help.
The blog's id appears on my address bar:
http://localhost:8080/#/admin/single-pattern/4LIS362IEWa7RKEv79g8
But it renders a blank page. I cant see my blog content.
This is my route path code. I've added a parameter of :id in my singlepattern. The SinglePattern component is where I will get the individual blog's data:
{
path: "/admin",
name: "admin",
component: Admin,
meta: {
auth: true,
},
children: [
{
path: "dashboard",
name: "dashboard",
component: Dashboard,
},
{
path: "manage-patterns",
name: "manage-patterns",
component: ManagePatterns,
},
{
path: "single-pattern/:id",
name: "single-pattern",
component: SinglePattern,
},
],
},
Here is my "ListPattern" component's code. ListPattern is where all my sewing blogs are displayed.
<template>
<div class="list-blogs">
<h1>LIST BLOG TITLES</h1>
<br />
<input type="text" v-model="search" placeholder="search blogs" />
<div
class="blog-cover"
v-for="pattern in filteredPatterns"
:key="pattern.id"
>
<div>
<router-link v-bind:to="'/admin/single-pattern/' + pattern.id">
<h3 style="cursor: pointer" v-rainbow>
{{ pattern.title | uppercase }}
</h3></router-link
>
</div>
<p
:style="'background-color: var(--lightgrey)'"
:inner-html.prop="pattern.description | snippet"
></p>
</div>
</div>
</template>
<script>
import firebase from "firebase";
import searchMixin from "../mixins/searchMixin";
// Basic Use - Covers most scenarios
import { VueEditor } from "vue2-editor";
import Quill from "quill";
const AlignStyle = Quill.import("attributors/style/align");
Quill.register(AlignStyle, true);
// import $ from "jquery";
import Swal from "sweetalert2";
window.Swal = Swal;
const Toast = Swal.mixin({
toast: true,
position: "top-end",
showConfirmButton: false,
timer: 3000,
});
window.Toast = Toast;
export default {
name: "ManagePatterns",
components: { VueEditor },
data() {
return {
patterns: [],
pattern: {
title: null,
description: null,
image: null,
},
search: "",
};
},
firestore() {
return {
patterns: firebase.firestore().collection("free-patterns"),
};
},
computed: {},
},
};
</script>
And this is my 'SinglePattern' component where the clicked blog/pattern is displayed.
<template>
<div class="single-pattern">
<div class="blog-cover">
<div>
</div>
<div v-if="pattern">
<h3 style="cursor: pointer">
{{ pattern.title }}
</h3>
<div v-if="pattern.description">
<p
:style="'background-color: var(--lightgrey)'"
:inner-html.prop="pattern.description"
></p>
</div>
</div>
</div>
</div>
</template>
<script>
import firebase from "firebase";
import searchMixin from "../../mixins/searchMixin";
export default {
data() {
return {
id: this.$route.params.id,
patterns: [],
pattern: {
title: null,
description: null,
image: null,
},
};
},
firestore() {
return {
patterns: firebase.firestore().collection("free-patterns"),
};
},
mixins: [searchMixin],
created() {
console.log(this.$route.params.id);
var pat = this;
firebase
.firestore()
.collection("free-patterns")
.doc(this.$route.params.id)
.get()
.then(function(doc) {
if (doc.exists) {
pat.pattern = doc.data().pattern;
} else {
console.log("no such doc");
}
});
},
methods: {},
};
</script>
It works. I just had to change the code in my created() hook in 'SingePattern' component.
created() {
console.log(this.$route.params.id);
var docRef = firebase
.firestore()
.collection("free-patterns")
.doc(this.$route.params.id);
docRef
.get()
.then((doc) => {
if (doc.exists) {
this.pattern = doc.data();
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch((error) => {
console.log("Error getting document:", error);
});

WordPress REST API not working when filtering by slug using Axios

I was able to display WordPress post content using axios and Vue.js. Once I switched to filtering by slug, I was unable to display post content.
<template>
<div>
<article>
<h2 class="subtitle">{{ post.title.rendered }}</h2>
<div v-html="post.excerpt.rendered"></div>
</article>
</div>
</template>
<script>
import axios from "axios";
import Router from 'vue-router'
export default {
name: 'ShowPost',
data () {
return {
post: []
}
},
created() {
this.slug = this.$route.params.slug;
},
mounted() {
axios({ method: "GET", "url": "https://wpdemo.stevensoehl.com/wp-json/wp/v2/posts?slug=" + this.slug }).then(json => {
this.post = json.data;
}, error => {
console.error(error);
});
}
}
</script>
It is necessary to check whether there is cross domain problem in the console, and there may be no cross domain problem
I figured it out a solution. In my links to an individual post I carried over the slug and id as params
<router-link :to="{name: 'ShowPost', params: {slug: post.slug, id:post.id}}">{{ post.title.rendered }}</router-link>
Route is slug and filter response by id. It now works as planned.
import axios from "axios";
export default {
name: 'ShowPost',
data () {
return {
post: []
}
},
created() {
this.id = this.$route.params.id;
},
mounted() {
axios({ method: "GET", "url": "https://wpdemo.stevensoehl.com/wp-json/wp/v2/posts/" + this.id }).then(json => {
this.post = json.data;
}, error => {
console.error(error);
});
}
}

Angular 4.0+ calendar http get to Asp.net core 1.1

I am working with this Angular 4 calendar:
https://mattlewis92.github.io/angular-calendar
I am trying to make a request to the api following the async method recommended in the github page, but it does not make the request unless if I use .toPromise(), but with that I do not know how to map
Here is my get of my calendar-component.ts:
params = new URLSearchParams();
options = new RequestOptions();
events: any[];
events$: Observable<Array<CalendarEvent<{ event: EventCalendar }>>>;
/***/
getEvents()
{
const getStart: any = {
month: startOfMonth,
week: startOfWeek,
day: startOfDay
}[this.view];
const getEnd: any = {
month: endOfMonth,
week: endOfWeek,
day: endOfDay
}[this.view];
this.params.set('beginning', format(getStart(this.viewDate), 'YYYY-MM-DD'))
this.params.set('end', format(getEnd(this.viewDate), 'YYYY-MM-DD'))
this.options.search = this.params
this.http
.request(ApiConfig.API_URL + 'calendar/RangeEvents', this.options)
.toPromise()
.then(() =>
{
res => res.json()
.map(({ results }: { results: EventCalendar[] }) =>
{
results.map((event: EventCalendar) =>
{
return {
title: event.title,
start: event.date,
color: colors.yellow,
allDay: true,
meta: {
event
}
}
})
})
})
}
I get the the request if I use this, but the html calendar does not get the events:
this.http
.get(ApiConfig.API_URL + 'calendar/RangeEvents', this.options)
.toPromise()
.then(response =>
{
this.events$ = response.json()
})
And I got this from Api:
{title: "Event 1", date: "2017-10-10T10:34:09"}
Html:
<mwl-demo-utils-calendar-header [(view)]="view"
[(viewDate)]="viewDate"
(viewDateChange)="fetchEvents()"
(viewChange)="fetchEvents()">
</mwl-demo-utils-calendar-header>
<ng-template #loading>
<div class="text-center">
<i class="fa fa-circle-o-notch fa-spin" style="font-size:40px"></i>
<br>
</div>
</ng-template>
<div *ngIf="events$ | async; else loading; let events">
<div [ngSwitch]="view">
<mwl-calendar-month-view *ngSwitchCase="'month'"
[viewDate]="viewDate"
[events]="events"
[activeDayIsOpen]="activeDayIsOpen"
(dayClicked)="dayClicked($event.day)"
(eventClicked)="eventClicked($event.event)">
</mwl-calendar-month-view>
<mwl-calendar-week-view *ngSwitchCase="'week'"
[viewDate]="viewDate"
[events]="events"
(eventClicked)="eventClicked($event.event)">
</mwl-calendar-week-view>
<mwl-calendar-day-view *ngSwitchCase="'day'"
[viewDate]="viewDate"
[events]="events"
(eventClicked)="eventClicked($event.event)">
</mwl-calendar-day-view>
</div>
</div>

Error WordPress REST API V2 call with Vue.js

I am getting the following error, when I make a call to WP REST API with Vue.js and axios.
XMLHttpRequest cannot load http://my-wordpress-site.com/wp-json/wp/v2/posts.
The 'Access-Control-Allow-Origin' header has a value 'http://null' that is not equal to the supplied origin.
Origin 'null' is therefore not allowed access.
When I use Postman with GET method, it is working correctly.
Where is the problem?
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>
I solved it by changing a line in wp-includes/rest-api.php file, in rest_send_cors_headers() function:
header( 'Access-Control-Allow-Origin: *');

Resources