VueJS and Axios POST- $_POST empty on server side - vue.js

I am at witts end with axios/vue currently, hoping someone can see something I am missing.
I am using axios documentation and doing a basic post.
axios({
method: 'POST',
url: 'myurlhere',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
The api is absolutely hit, I am logging it on the server side. The console log on the axios side does not throw any errors. I am printing out the $_REQUEST variable on the server side just to see what is coming through and the $_POST is empty. The console log does show the returned array but post is empty.
<?php
$data=array('worked'=>true,"data"=>$_REQUEST);
echo json_encode($data);
?>
If i use $_GET variables they work. Post does not though. what am I doing wrong???

Related

How to pass formurlencoded values in post method

Here is my code
axios
.post(
'https://app.adhg.ashdg/m/api/business/get-business',
{
'gid': getgid,
},
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
// handle success
alert(JSON.stringify(response.data));
})
.catch(function (error) {
// handle error
alert(error.message);
});
I am using Axios to fetch data from API but I am not getting response. I have tried some of the suggestions available in Stack Overflow and from web searches, but nothing helped me. I am getting error like "invalid parameters".
I also tried in Postman with the same parameter and I am getting response. What mistake am I making?
Note
Expected output: I have to get the output like status:1,msg:'success'.
What I am getting is like status:0,msg:'Invalid parameters'

Problem put axios update user Strapi and NuxtJS

I have a problem with the right in strapi.
I create user with the role Authenticated and try modified the data with axios.
But it is impossible has modified because return forbidden. I look if the user has right, Update is check in role authenticated.
If i check update in role public, my modification with axios is ok. Why ? I don't undestand the problem.
My code for send
.put(
`https://localhost:4000/users/${this.data.id}`,
{
headers: {
Authorization: `Bearer ${token}`
},
Nom: 'JEAN'
}
)
.then((res) => {
// Handle success.
console.log(res)
})
.catch((error) => {
// Handle error.
console.error('An error occurred:', error)
})```
Thank you
I'm not sure the axios request has the right format.
According to this documentation - https://github.com/axios/axios#axiosconfig
This probably should look like this:
axios({
method: 'put',
url: `https://localhost:4000/users/${this.data.id}`,
data: {
username: 'JEAN'
},
headers: {
Authorization: `Bearer ${token}`
}
});

how to use axios to send data to line notify

I tried to send data to line notify server by axios and it fail
I have tried 2 version of code. as shown below
version 1 :
axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
data: 'message="from vue"',
config: {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
}
},
Authorization: "Bearer [my token]"
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
console.log(response);
});
response is
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
and version 2 is :
axios
.post("https://notify-api.line.me/api/notify", "message=from vue", {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer [my token]"
}
})
.then(response => {
console.log(response);
});
response is
Preflight response is not successful
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
What wrong with is
but I have tried in postman it work fine
Oh I am too familiar with this. Heres an explanation on stackoverflow as to why your request works with postman but not in browser. Long story short browsers send a preflight options check that will ask the server if the action you're about to perform is allowed. Postman does not. Usually the "Access-Control-Allow-Origin": "*" header is sent by the server to the browser not the other way around.
Inside the docs for LINE Notify you can find:
POST https://notify-api.line.me/api/notify
Sends notifications to users or groups that are related to an access token.
If this API receives a status code 401 when called, the access token will be deactivated on LINE Notify (disabled by the user in most cases). Connected services will also delete the connection information.
Requests use POST method with application/x-www-form-urlencoded (Identical to the default HTML form transfer type).
My guess is that your access_token might have been deactivated. Try requiring a new access token and doing the request again.
I think it is impossible to connect directly to the external url for the axios cuz ajax is basically for the inner data network. But you might have a controller if you do a web project, so you can just use your controller language to make a connection with line notify. In my case, I made a rails project and used axios in the vue.js, so I made a link like this.
View(axios) => Controller(Ruby) => LineAPI
me currently work on this too.
I did my app with node js.
My way below is for your reference, it works well.
const axios = require('axios');
const querystring = require('querystring');
axios({
method: 'post',
url: 'https://notify-api.line.me/api/notify',
headers: {
'Authorization': 'Bearer ' + 'YOUR_ACCESS_TOKEN',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
data: querystring.stringify({
message: 'something you would like to push',
})
})
.then( function(res) {
console.log(res.data);
})
.catch( function(err) {
console.error(err);
});
I try it works.
async function test() {
const result = await axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer [token]",
},
data: 'message=你好哇'
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
}
test();
I think you can check response on chrome debugger network.
or provide more information, thx.

Post data to API in React Native only show empty

I am building an application in react native CRNA for the front-end side and using PHP for the backend side. But when I tried to post a data, for example login form, the result is only empty no matter what the given input is.
This is an example of my snippet code.
fetch('someURL', {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message,
})
})
.then((response)=>response.json())
.then((responseData)=>{
Alert.alert(console.log(responseData))
return responseData;
}).catch((error) => {
console.error(error);
});
}
I tried to check the value with console.log and didn't get anything (only empty).. What should I do? Can anyone please tell me what's wrong? Thank you so much.
Try to remove the first then() and put the response.json() into the next then(). In the same block as the Alert.

How to check if body in fetch POST has sent to API in react native?

I am building a react native app and got this following error. I want to send inputted message, email, and name to API, but it's not showing any result in API.
Here is the code:
fetch('localserverusingIPaddress', {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message,
}),
})
.then((response)=> {console.warn(response.json())})
//{
// if (response.status){
// return response.json();
// }
// console.warn(response.json())
// return response.json();
//})
//console.warn(response);
//response.json()
//console.warn(JSON.parse(response))})
.then((responseData)=>{
this.showAlert();
console.warn(responseData);
return responseData;
})
.catch((error) => {
console.warn(error);
});
However, when I try to check the inputted texts in iOS
simulator, it's showing the value. It's also showing the values when I post data to API directly with postman. So I start to think that the body was failed to pass to API.
Can anyone please tell me why is this happening and how to fix this? Thank you so much, I'm facing this problem for several weeks...
First step is to make sure if your iOS simulator is actually able to make requests to your localhost or not. If it can't reach your local network, it must throw some kind of connectivity error. However, from your comment above, it seems that is not an issue.
Try this code:
let url = 'localserverusingIPaddress';
let requestObject = {
name: this.state.name,
email: this.state.email,
message: this.state.message
};
try {
let response = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(requestObject)
});
responseJson = await response.json();
console.log(responseJson);
} catch (error) {
console.error(error);
}
Try this and see what is the logged output.
Easiest way to see if the request has actually reached your API is from the API end itself. Your server must have some sort of event logging implemented. See what happens there when you make a request from Postman and compare its output with what happens when you make a request from the app.