Axios POST request not working when passed object - vue.js

I am trying to do a post request in a vue js app using axios to a local API and the response is returning empty data. The post request on API is working fine using Postman tool. Below is my code
var the_data = {
title: 'This is title',
description: 'this is description'
}
axios.post('/api/snippets/insert', the_data)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
On the API end, I am using a simple PHP script and printing whole $_POST request data using this code
var_dump($_POST);
But this is returning empty array.

I was running into this as well. Axios does not send the POST data in the form you're expecting. You need something like http://github.com/ljharb/qs and then use axios.post('/api/snippets/insert', Qs.stringify(the_data)). Please note this build on cdnjs uses Qs, not qs.
Alternatives to qs would be e.g. JSON.stringify() or jQuery's $.param().

Related

how solve 404 error in axios post request in vue?

i want send request to an api but i have 404 erro and i have nothing in network
can you help me?
my code:
loginMethod() {
const config = {
userName: "test#gmail.com",
password: "1234test",
};
return new Promise((resolve) => {
ApiService.post("api/authentication/login", config)
.then(({ data }) => {
console.log(data);
resolve(data);
})
.catch(({ response }) => {
console.log(response);
});
});
},
and ApiService function:
post(resource, params) {
console.log(params);
const headers = {
"E-Access-Key": "bb08ce8",
};
return Vue.axios.post(`${resource}`, params, { headers: headers });
},
Based only on what I can see in your code, you are not telling axios the complete URL if I'm right about it, and you didn't declare it somewhere else do this:
axios.post('yourdomain.com/api/authentication/login',params)
or
axios({
url:'yourdomain.com/api/authentication/login',
method:post,
data:{}
})
or
in your main js file or any other file that you import axios (if you are sharing an instance of it globali):
axios({baseurl:'yourdomain.com'})
and then you don't need to write the complete url everywhere and just insert the part you need like you are doing now and axios will join that address with the baseurl,I hope it helps
I guess the URL "api/authentication/login" might be wrong and the correct one would be "/api/authentication/login" that starts with /.
404 error means the resource referred by the URL does not exist. It happens when the server has deleted the resource, or you requested a wrong URL accidentally, or any wrong ways (e.g. GET vs POST)
To make sure if you were requesting to the correct URL (and to find where you're requesting actually), open Google Chrome DevTools > Network panel. You might need reload.
The url api/xxx is relatively solved from the URL currently you are at. If you were at the page http://example.com/foo/bar, the requested URL becomes http://example.com/foo/bar/api/xxx. Starting with / means root so http://example.com/api/xxx.
This answer might help to understand the URL system: https://stackoverflow.com/a/21828923/3990900
"404" means your API Endpoint is not found. You need to declare the location of your API Endpoint exactly. For example: http://localhost:8080/api/authentication/login.

GET Request fails in Vuejs Fetch but works perfectly in Postman and in browser due to 302 redirection

I have a web application built using NuxtJS/Vuejs within that I have a field where user can provide the URL and my application should make a GET request to that URL and obtain the data. Mostly the URL is related to GitHub from where it should fetch XML/JSON the data.
When I provide a certainly URL in browser/Postman then the redirection happens and data from the redirected URL is loaded. I want to achieve the same in my code but it's not happening and I get the error:
index.js:52 GET {{URL}} net::ERR_FAILED 302
But these URL works perfectly in browser and in Postman without any issue. Following is my code where I am making the request using Vuejs Fetch:
fetch(inputURL, {
method: 'GET'
})
.then((response) => {
console.log('RESPONSE')
console.log(response)
})
.catch((error) => {
console.log('ERROR')
console.log(error.response)
})
Using the Axios:
axios
.get(inputURL)
.then((response) => {
console.log("RESPONSE");
console.log(response);
})
.catch((error) => {
console.log("ERROR");
console.log(error);
})
I tried setting various header, I tried using axios etc but nothing seems to work for me. Can someone please explain to me what am I doing wrong and how to fix this issue? Any help or workaround would be really appreciated.
First of all, the 'Access-Control-Allow-Origin' header is something that should be set up on the server side, not on the client making the call. This header will come from the server to tell the browser to accept that response.
The reason why your code works from postman/browser is because you're not under the CORS rules when you request it like that.
One way around it, would be to make a call to your backend and tell the backend to call GET the data from the URL provided and then return it to your front-end.
Example:
//call_url.php
<?php
$url = $_GET['url'];
$response = file_get_contents($url);
echo $response
?>
//vue.js component
<input type="text" v-model="url"></input>
<button type="button" #click="callUrl">call me</button>
...
methods: {
callUrl() {
axios.get('call_url.php?url=' + encodeURIComponent(this.url))
.then(response => {
//...do something
}
}
}
As mentioned in another answer it's not possible for any library including Fetch and Axios to make requests and obtain the Data due to various security policies. Hence, I created a method in my Spring boot application that will obtain the data from URL and I make a request to my Spring boot using Axios.
import axios from 'axios'
axios.post('/urlDataReader', inputURL)
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
Spring boot app:
//Method to read the data from user-provided URL
#PostMapping(value = "/urlDataReader", produces = "text/plain")
public String urlDataReader(#RequestBody String inputURL) {
final String result = new RestTemplate().getForObject(inputURL, String.class);
return result;
}

Display data from Twitter API using axios

I got stuck with a Vue project. I need to display 10 tweets in a component with the hashtag "Vue", so I am trying to pull data (username, tweet, date) from Twitter API. I read the twitter dev documentation, googled for hours, but it all suggested a php or python script for handling this request. Isn't it possible with axios? I got the following code, but the server always responds 400.
Here is my sample code (the keys are mocked):
import axios from "axios";
var api_url = "https://api.twitter.com/1.1/search/tweets.json?q=from%3Atwitterdev&result_type=mixed&count=2";
var AUTH_OBJ = {
oauth_consumer_key: "CONSUMER_KEY",
oauth_nonce: "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
oauth_signature: "tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: "1318622958",
oauth_token: "TOKEN_FROM TWITTER_DEV",
oauth_version: "1.0"
};
axios.defaults.headers.common["Authorization"] = AUTH_OBJ;
function getData() {
axios.get(api_url)
.then(function (response) {
console.log(response)
});
}
Could someone please help?

Using fetch() with API

I try to use fetch() to get the data from https://swapi.co/
With this code I get undefined but in the "Network" section in chrome I see the data I need. How I can access it?
fetch('https://swapi.co/api/people/1/')
.then(resp => resp.json)
.then(obj => console.log(obj));
Hello this will fetch the data returning it as json
fetch('https://swapi.co/api/people/1')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
If you have right environment for calling to the fetch API there maybe 2 result
You will get the right result data
You will get an error
fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
// Your code for handling the data you get from the API
})
.catch (function() {
// This is where you run code if the server returns any errors
});
Use a catch for seen what is going wrong with your request

Call API with Another Api response data in Nuxtjs

Im making a website with Nuxtjs, i want when i open any page of the website to get user information from the server using Axios, and i want to use these information to call another API's from the website.
For example: i will get the User id and Client id from the server and use them on the API URL, lets say i got User id = 5, Client id = 10
i will call another API's and use these informations
http://****/getItems?userid=5&clientid=10
Now my problem is the second API call before the first API finished so i didn't got the user informations yet.
Could you please help me with this issue, note that i want to get the user information on all pages. so if i reload the page in any page i want to get user informations.
So i call the user information API from a Layout and call the other API's from another components.
Thanks.
First you should use Axios module officially provided by Nuxt.js here, https://github.com/nuxt-community/axios-module. They have make the integration between Axios and Nuxt.js easier.
Axios uses promise so you can easily chaining method to do it. Let say you wanna get information from /get/product with data gotten from the url you mention before http://****/getItems?userid=5&clientid=10, you can easily do that like this
this.$axios.$get('/getItems?userid=5&clientid=10')
.then(data => {
// You can use your data received from first request here.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
})
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
Explanation
This part,
this.$axios.$get('/getItems?userid=5&clientid=10')
the axios will get the data from the url provided, when the data is received, we can use it within then() block as it accept callback as a parameter.
.then(data => {
// You can use your data received from first url here.
...
})
After that, if you wanna use your data you can easily return the axios request again with proper parameter you wanna send.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
And again you can use the data received from second axios request within then() block.
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
Updated
Oke, based on the clarification on the comment section below. We can return the axios promise in first action and then on the second method we can dispatch the first action,
actions: {
callFirst ({ commit }) {
return this.$axios.$get('/get/first')
.then(firstResult => {
commit('SET_FIRST', firstResult)
return firstResult
})
},
callSecond ({ dispatch, commit }) {
return dispatch('callFirst').then(firstResult => {
return this.$axios.$post(`/get/${firstResult.userId}`)
.then(secondResult => {
commit('SET_SECOND', secondResult)
return secondResult
})
})
}
}
Using that way, you just need to put the callSecond() action whereever you want get the second data. And you also don't need to put the callFirst() action on default.vue.