I tried these code to post data using Axios Api in Vue in I am getting these error:
Access to XMLHttpRequest at 'https://jsonplaceholder.typicode.com/todos' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 16_Axios_API_CRUD.html:96 Error: Network Error at e.exports (spread.js:25) at XMLHttpRequest.l.onerror (spread.js:25)
new Vue({
el: "#app",
data() {
return {
todos: [],
newTodo: "",
loading: true,
errored: false
};
},
methods: {
addToDo() {
debugger;
const _todo = {
title: this.newTodo,
completed: false
};
//const { title } = this.newTodo;
axios
.post("https://jsonplaceholder.typicode.com/todos", _todo)
.then(res => (this.todos = [...this.todos, res.data]))
}
},
mounted() {
axios
.get("https://jsonplaceholder.typicode.com/todos?_limit=5")
.then(response => (this.todos = response.data))
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<div id="app">
<input
v-model.trim="newTodo"
/>
<input
value="Add"
type="button"
v-on:click="addToDo"
/>
<section v-else>
<div v-bind:key="todo.id" v-for="todo in todos">
<div class="todo-item" v-bind:class="{'is-complete':todo.completed}">
<p>
{{todo.title}}
</p>
</div>
</div>
</section>
</div>
Anyone face this error message before? Do I need destructor which I notice in some tutorial before posting it? Not quite sure why some tutorial have destructor though.
Edit: It looks like 'slow processing' issue. I can the posted data after a long time. How do I add some 'animation' to show that it is actually in progress posting the data and in progress of returning it back?
You are using absolute URL's. There are two ways you can handle this.
If you choose the second, which is recommended over the other, your code will be like this:
axios
.post("/api/todos", _todo)
.then(res => (this.todos = [...this.todos, res.data]))
And in your reverse-proxy, made possible by webpack-dev-server:
module.exports = {
//...
devServer: {
proxy: {
'/api': 'https://jsonplaceholder.typicode.com'
},
secure: true
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With