We are making an axios POST call from VueJs, need to pass a custom header. The way it is coded now, the custom header is not getting passed to the server script, other headers are getting passed. Please let me know what I might be doing wrong. Appreciate your help.
axios({
method: 'post',
url: urltocall,
data: strjson,
config: {
headers: {
'Access-Control-Allow-Origin': 'http://localhost:1337',
'Accept': 'application/json',
'Content-Type': 'application/json',
'username': 'test1'
}
}
})
.then(function (response) {
}
The headers object should not be put into a "config" object.
It's just...
axios({
method: 'post',
url: urltocall,
{
headers: {
....
Try doing it like this:
axios
.post(urltocall, myDataAsJSON, {
headers: {
"Access-Control-Allow-Origin": "http://localhost:1337",
"Accept": "application/json",
"Content-Type": "application/json",
"username": "test1"
}
})
.then(response => {
console.log("Success: " + response.data);
})
.catch(error => {
console.log("Error: " + error.response.data);
});
By the way, based on your 'Content-Type': 'application/json',, I know you're trying to send a JSON object, but where/what is this object?
Also, refer to the Full documentation for more information.
Related
When I call API I am getting below error in response. please find below is code and error message.
TEST RESPONSE:
{
"responseData": {"limit": ["Limit is required"],
"module_type": ["Module type required"],
"section": ["section value \"liveability || investment || recommend\" is required"],
"skip": ["Skip is required"]
}
Implemented code:
fetch( 'https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
Try this way
import FormData from 'FormData';
...
var data = new FormData();
data.append("skip", "0");
data.append("module_type", "buy");
....
fetch('YOUR_URL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
})
.then((response) => response.json())
.then((responseJson) => {
console.log('response object:',responseJson)
})
.catch((error) => {
console.error(error);
});
Sometimes when you work with REST API call you have to work with correct headers.
In your case I suppose your are missing two important headers required to activate a good communication between client and servers:
accept
content-type
Please review your code based on this one:
fetch('https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
headers: {
"accept": "application/json",
"content-type": "application/json"
},
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
I think the server is returning "missing" parameters because is not able to understand the type of content. With Content-Type you should be able to instruct the server on how to parse your data.
i'm studying with React Native,
but i can't get response properly
my fetch code is :
try {
let response = fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log(response);
the response is :
the api response which i get from api when i try postman:
my php api is :
but my debugger console response is
fetch() function return a promise, so you should resolve this promise using one of this 2 methods:
1/ Using .then()
fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
).then(response => {
console.log(response); //<- your response here
}).catch(error => {
console.log(error); //<-catch error
});
2/ Using async/await syntax: you should add async keyword on the function where you call fetch
async getResponse(){
try {
let response = fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log(response); //<- your response here
} catch(e){
console.log(e);<-catch error
}
}
You can send it using formdata:
let formData = new FormData();
formData.append('firstname', 'test');
If you do this, you don't have to use JSON.stringify:
fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: data
}
...
fetch is an asynchronous method, meaning it needs a .then callback. The data that immediatley comes from this then has a json() method attached to it to retrieve the actual data in a readable format.
fetch("http://192.168.1.106/little_api/index.php", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response => response.json())
.then(data => {
console.log(data) // this should return your data
})
.catch(err => console.log(err))
As Mahdi N said in his response, you can use the async/await syntax to retrieve the data without needing the nested callbacks.
I try to fetch webservice method. However, it takes string. How can I send string parameter to webservice ?
I tried like this :
fetch('url/MethodName', {
method: 'POST',
headers: new Headers({
Accept: 'application/json',
'Content-Type': 'application/json',
}),
})
where should I put string parameter ?
by mozilla
var url = 'https://example.com/profile';
var data = {username: 'example'};
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
send Json data as parameter
You can do that with fetch, but try to use Axios for making http requests
https://kapeli.com/cheat_sheets/Axios.docset/Contents/Resources/Documents/index
I'm posting to an API using axios, and using the data from the response I want to make another API request but I'm running into issues saying that axios is not defined.
The calls, that are in inside my Vue login component, are the following:
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
and as I mentioned earlier, the error in my console is the following: TypeError: Cannot read property 'axios' of undefined.
I´ve tried writing the second request without this. but I'm having the same issues. Where am I going wrong?
You have to use an arrow function here.
Regular functions have their own this value.
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
Or if you prefer old-fashioned way you can save this reference to some variable to have access to it in the callback:
const self = this
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
self.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
I am trying to learn react native application by making a simple login page using api call. Where I will send user name and password to api and it will give me response. But I can't do it. Well I am sharing my code here.....
var myRequest = new Request('<my API >', {method: 'POST', body: '{"username":this.state.uName , "password":this.state.pwd}'});
fetch(myRequest).then(function(response) {
alert('Res'+response);
}).then(function(response) {
alert('Blank'+response);
})
.catch(function(error) {
alert('Error'+error);
});
I think the way of passing my user name and password to server is wrong. Please give me some idea then I can understand what is wrong here.
var data = {
"username": this.state.username,
"password": this.state.password
}
fetch("https://....", {
method: "POST",
headers: headers,
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
I hope this helps.
You need to Stringify the json data to send request as Post method with Json parameters as you are trying to do...
Here is the example code for how to encode data before requesting for response
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
Here is the sample code for login :
fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ userName: <userName> ,Password: <Password>,})
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
}).catch((error) => {
console.log("Error");
});
As the commentators before me stated, you simply need to stringify your JSON Body. In general, I' suggest that you incorporate e.g. api sauce into you stack. It is a comprehensive wrapper around the axios library, providing standardized errors and an ok key for quick checks.