Axios AJAX call nulls parameter - ajax

I use Vuejs to create my frontend for my project.
At the creation of one component ('TimeCapsy.vue'), I make an AJAX call to my backend like this:
created: function () {
if (verify.verify_login()) {
let token = this.$cookies.get('jwt_us_cas');
let params = {'jwt': token};
console.log(params);
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
params: queryString.stringify(params)
})
.then(response => {
console.log(response.data)
})
}
}
As you can see I use the
this.$cookies.get('jwt_us_cas');
to get the a json web token, that I set on the client at the login.
I use the queryString Library to stringify my parameters for my request.
I also tried it without the queryString.stringify(params) call, but I get the same error, e.g. the parameter still turns into null.
When I look at the console log, where I check the params variable, I get this output:
{jwt: "my token comes here"}
So I can see, that it gets the correct value from the cookie.
But when I check the answer from my backend (PHP), I get this error:
Undefined index: jwt in <b>D:\casb\public\index.php</b> on line <b>52</b>
Of course I know that it means, that jwt is null, but I can't understand why.
As I said, right before I make the call I check the params and it shows the token.
I checked the endpoint with Postman and the token as the jwt parameter and it returned a successfull call with the correct answer.
A correct answer is basically just a nested object with some information in it.
My PHP endpoint is pretty basic too:
Router::add('/getuserinfoobject', function () {
$response['response'] = User::getUserInfoObject($_POST['jwt']);
echo json_encode($response);
}, 'post');
So I guess that right before or in my call it nulls my parameter. But I can't understand how, since I make a lot of requests and never had this problem.

From axios docs
params are the URL parameters to be sent with the request
Which means, you should get the value with PHP $_GET.
Or $_REQUEST (which stores both $_GET, $_POST. Also $_COOKIE).
The other hand, you can use data key as docs says
data is the data to be sent as the request body
Only applicable for request methods PUT, POST, and PATCH
So the value would be available in $_POST
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
data: {
jwt: token
}
})

Related

Getting Myob AccountRight API Access token error

I am trying to get access token from MYOB. The POST call i make returns a "400 Bad Request error"
i'm using "axios" to make the POST call
i already got the Access code which i use in the data i'm sending in the POST call
here is my code
const config= { headers:{'Content-Type':"application/x-www-form-urlencoded"}}
const data={
client_id:"xxxxxxxxxxxxxxxxxxxxxxx",
client_secret:"xxxxxxxxxxxxxxxxxxxxx",
scope:"CompanyFile",
code: code,
redirect_uri:"http%3A%2F%2Flocalhost%3A30002Fcallback",
grant_type : "authorization_code"
}
axios.post("https://secure.myob.com/oauth2/v1/authorize", data, config)
.then((res) =>{
console.log ("response ...............", res
}
)
.catch((error) => {
console.error("Error here is ........",error)
}
)
Axios will, by default, attempt to POST your data fields as JSON which is not correct.
Instead, you want to url encode them and post the url-encoded string in the HTTP body. See the 'example call' in the docs.
There's a good example of how to url encode w/ axios here.
I also note that your redirect_uri field is already url encoded, so attempting to simply encode it a second time means you'll end up with something like http%253A%252F%252Flocalhost which is not correct. Double check your URL encoding against the example call to make sure you're not accidentally encoding certain fields twice. From memory the access code is already encoded appropriately so you might need to fiddle with decoding it before re-encoding it to get it working.

POST request doesn't get response from server in chrome but work in postman

I'am making a POST request to spring boot endpoint and wanna get data return from server.With testing my API in Postman,it works good.but when testing it in
chrome,it doesn't even get a response and chrome NETWORK bar even did't have record.
so code is simple,I can't find any problem,RestController
#PostMapping("/signup")
public User signup(#RequestBody ModelUser user){
//fetch data from DTO and craft a user
User userData=user.adapter();
//...code here omit for sake of brevity
return userData;
}
it indeed get data from ajax,when I use logger(slf4j) to debug.
and ajax:
$("#sign-up").submit(function () {
var userInfo={}
userInfo["phone"]=$("#phone").val()
userInfo["password"]=$("#password").val()
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
}).then(
function(){
//this doesn't print in console
console.log("Hello Callback is executed")
}
)
})
weird as it is,I never encounter this when I use GET request,since ajax callback is successfully called when I use GET to test a GetMapping endpoint.
oh,with lots of similar questions
AJAX POST request working in POSTMAN but not in Chrome
Angular 4 POST call to php API fails, but GET request work and POST requests work from Postman
POST response arrives in Postman, but not via Ajax?
I don't get any response status code in chrome and completely not involved CORS in question
Have you tried adding a consumes and produces media type of Json in the Java
#PostMapping(path="/signup", consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
And explicitly set the Accept header in the javascript
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
headers: {Accept : "application/json"},
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
})
I'am sorry for my poor front end skill,the main reason is that I don't understand Javascript event.
$("#sign-up").submit(function (e) {
//e.preventDefault();
var user={};
user["phone"]="187308";
user["name"]="icywater";
$.ajax({
type:'POST',
contentType:'application/json',
data:JSON.stringify(user),
url:"http://localhost:8080/test"
}).done(function(data){
console.log("Hello Callback is executed");
console.log(data)
});
});
here when I click submit It actually already submit the form and don't wait ajax code to be executed,so I should use e.preventDefault()to suppress default behavior.It's nothing
related about POST or postman ,it is about the form submit default behavior,ahh,Oolong event.
I got it when I found this page

Beego not accepting ajax params

I'm trying to make simple POST request using VueJS to an application which is written in Beego framework (GoLang) but the application doesn't see any input request. Everything is ok when I use standard form request (no ajax).
This is my VueJS code:
storePost: function(event) {
axios.post("/api/posts/store", {body: "test"}).then(function(response) {
if (response.data.status == 200) {
this.posts.push(response.data.data);
}else {
console.log("error");
}
}, function(response){
console.log("error");
});
}
and this is my Beego code:
// router.go
beego.Router("/api/posts/store", &controllers_API.PostsController{}, "post:Store")
// PostsController.go
func (this *PostsController) Store() {
fmt.Println(this.GetString("body"))
// some irrelevant code which handles the response...
}
fmt.Println always prints nothing. When I use standard forms fmt.Println prints the value of the body with no problems.
It seems that Beego only accepts data with this header: 'Content-Type': 'multipart/form-data' so after I added that header everything was ok.
Since I didn't know how to do that with axios I switched to vue-resource and this is the example code which works with Beego:
this.$http.post("/", {test: "test"}, {
emulateJSON: true
});
Now you can print it like this:
fmt.Println(this.GetString("test"))
I hope this helps someone
Just verified that axios and vue-resource use application/json by default. The emulateJSON you use here tells vue-resource to use application/x-www-form-urlencoded. You probably just need to do a json decode in beego because it by default treats request body as urlencoded.
multipart/form-data works probably because it's been there for long(like urlencoded) so beego by default recognizes it. To use vue-resource to post a multipart/form-data request: use FormData. Axios also accepts a FormData as data.

sendAJAX data parameter in CasperJs

again, I got another problem with casperjs, now with sendAJAX function.
It says that sendAJAX has 5 parameters which are these followings :
url: The url to request.
method: The HTTP method (default: GET).
data: Request parameters (default: null).
async: Flag for an asynchroneous request? (default: false)
settings: Other settings when perform the AJAX request (default:
null)
So, it says the data method is object so, it should be filled with :
var data = new Object();
data.amount= 15;
and also with this one,
var data = {amount:15};
but there were no successful value send to my web service (always send 0 as value, but ajax request successful, even returning the json data) which has an url like this
"http://localhost:9000/TempCountryAmountREST/setCountryAmount"
It will be succeed if I direct bind my data variable to my url like this :
"http://localhost:9000/TempCountryAmountREST/setCountryAmount?amount="+amount
[UPDATE]
The TempCountryAmountREST is my controller name and setCountryAmount is my function inside my controller.
[UPDATE]
I forgot to include my usage of sendAJAX(), here is the code that I use :
return JSON.parse(__utils__.sendAJAX(wsurl, "POST" , data, false, { contentType: "application/json" }));
So how does I fill the data in the sendAJAX parameter?
Thanks in advance...
Sorry, I've found what the answer is.
I make some mistakes in contentType which I was set with contentType: "application/json" instead of contentType: "application/x-www-form-urlencoded" }
If we are looking about how ajax send the content from method send(), they were use x-www-form-urlencoded. See this for more detail
When we see through casperjs clientutils.js script, we should found how sendAJAX work.
On the `this.sendAJAX = function sendAJAX(url, method, data, async, settings) {
}
there are url construction logic which transformed our Object (if so) to x-www-form-urlencoded form. So that we need to set our contentType as application/x-www-form-urlencoded
Very well, thanks for your attention...

A 405 status code from web API after trying to send PUT data in body

ok.
I'm using Web API to make AJAX requests.
I'm trying to send a PUT request to an action on a controller.
I'm using route attributes.
When I'm sending the data as part of the route data, everything is fine and the action gets the right info.
However, when I'm trying to send the data in the body, I get a 405 status ((Method is not allowed).
I'm also adding the [FromBody] attribute to the parameter. Here's by jQuery call:
type: 'PUT',
url: 'api/ServerQueue/activity',
data: "=2",
success: function (xhr) {
$("#load").hide();
},
error: function () {
$("#load").hide();
}
};
Here's my action:
[Route("status/{status}")]
public string PutStatus([FromBody]int status)
{
}
I placed a "RoutePrefix" on the controller body.
BTW, I'm using VS 2012.
Any idea what could be the source of the problem?
Try changing the route configuration from
[Route("status/{status}")]
to
[Route("status")]

Resources