Beego not accepting ajax params - ajax

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.

Related

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

Axios AJAX call nulls parameter

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
}
})

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")]

Crossdomain post with easyXDM

I'm trying to get a crossdomain post to work. I know I can easily use jsonp for GET, but I'm stuck as to how I can implement POST requests.
I've looked up easyXDM, but as I understand it the server also needs some kind of easyXDM implementation, in the form of a "cors" file or something.
Is that true? So if the server does not support it, there's no way to do a crossdomain post (without setting up a proxy, that is)
I've tried it myself with only local files:
<script type="text/javascript">
var xhr = new easyXDM.Rpc(/** The channel configuration*/{
remote: "name.html"
}, {
remote: {
request: {} // request is exposed by /cors/
}
});
</script>
And then do a request like this:
xhr.request({
url: "http://other.domain.be",
method: "POST",
data: {NEWS: "true", IMMO: "true" }
}, function(response) {
alert(response.status);
alert(response.data);
});
But that does nothing.
Yes, easyXDM.Rpc need to be initialized using the server cors url.
xhr = new easyXDM.Rpc({remote: "http://url/cors"}, {remote:{request:{}}});
If you don't want to use easyXDM, you can easily set up the server to accept all requests by adding : (doesn't supported by IE<8)
Header set Access-Control-Allow-Origin *
Header add Access-Control-Allow-Headers X-Requested-With
Header add Access-Control-Allow-Headers X-Request

Spring 2.5.4 return a integer on ajax request

I am working on a spring 2.5.4 project, where I need to get an ajax response that returns a integer value on ajax request. Is there is some way I can do it?
For now, I believe all ajax calls either returns a page or a part of page.
The sample code I am using for ajax request with prototype is as follows,
var ajaxSourceTable = new Ajax.Request(
'../fetch/timeout.html?ajax=true',
{ method:'post',
parameters:{},
onSuccess:function(t){
/*alert time out here*/
alert(t.responseText);
},
onFailure:function(t){
alert("Request failed ! Please report the issue : "+t.responseText);
}
}
);
Your ../fetch/timeout.html?ajax=true has to return the single value. You should rather write a controller for that which return text/plain or application/json with the data in the response body.

Resources