Beego POST request body always empty - http

I'm working with Beego's convenience methods for parsing request body values and have the following:
Router file:
apiNamespace := beego.NewNamespace("/api")
apiNamespace.Router("/sessions/google/new", &controllers.SessionsController{}, "get:GoogleNewSession")
beego.AddNamespace(apiNamespace)
Controller code:
func (c *SessionsController) URLMapping() {
c.Mapping("GoogleNewSession", c.GoogleNewSession)
}
func (c *SessionsController) GoogleNewSession() {
// Always serve JSON
defer func() {
c.ServeJson()
}()
// This is always blank
log.Printf("'Received %+v'", c.Ctx.Input.RequestBody)
c.Ctx.ResponseWriter.WriteHeader(200)
return
// truncated
}
Front end JS (super-agent):
request
.post('/sessions/google/new')
.use(prefix)
.send({ code: authCode })
.set('Accept', 'application/json')
.end(function(err, res){
console.log("******* request", res.request)
if (res.ok) {
var body = res.body;
console.log('yay got ' + JSON.stringify(res.body));
} else {
console.log("***** err", err);
console.log("***** not ok", res.text);
}
});
When the superagent request fires off, I can see in the logs that the path is getting correctly matched. However, the c.Ctx.Input.RequestBody is always empty.
I have tried using something else to fire the request such as Postman but to no avail. In GET requests I am able to retrieve query params correctly.
Any clues or suggestions to help fix or debug this issue?

You need to configure "copyrequestbody = true" in configuration file "conf/app.conf".
The default is false so the content is not copied to c.Ctx.Input.RequestBody.
The example is shown section "Retrieving data from request body" in the document. (http://beego.me/docs/mvc/controller/params.md)

Related

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0?

I am trying to fetch local api made in asp.net api which is running in https://localhost:44388/. When I tried to fetch get request it responds ok but return html not json. The problem might occur by two reasons:
1.typo in url (But I checked in my browser, it worked)
2.Server restart needed
What might be the problem with my code?
componentDidMount(){
var proxyUrl = "http://127.0.0.1:3000/";
var targetUrl = "https://127.0.0.1:44388/api/product/getproducts";
fetch(proxyUrl+targetUrl, {
method:'GET',
headers:{
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Mehods': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials':'*',
'Content-type':'application/json'
}
})
.then(data=>{
if(!data.ok){
throw new Error("Error");
}else{
return data.json();
}
})
.then(data=>this.setState({products:data}))
}
when you give parameter as:proxyUrl+targetUrl,
actually the url which you have called is :
http://127.0.0.1:3000/https://127.0.0.1:44388/api/product/getproducts
which does not seems to be correct.
i think the structure of url you'v given to fetch function is wrong.

angular2 http delete

I use http.delete for remove my data.
This code in my service [MyService]:
deleteData(id){
let headers = new Headers(),authtoken = localStorage.getItem('token');
headers.append("Authorization", 'Bearer' + authtoken);
headers.append('X-Requested-With', 'XMLHttpRequest')
headers.append('Content-Type', 'application/json;')
return this.http.delete('http://link/'+id, { headers: headers })
.map((resp:Response)=>resp.json())
.catch((error:any) =>{return Observable.throw(error);});
}
This code in my component:
private delete(id):void{
console.log(id); //show`s id
this.myService.deleteData(id)
.subscribe((data) => {console.log(data)});
}
Show`s error "caused by: A network error occurred". My mistake was elsewhere. It is work.
There is nothing wrong in your code what i can see and you are not getting any error from server either. Try to call the same end point from postman and match the headers and check your Internet connection.

How to access Response cookies in angular2?

I'm trying to access this cookies (the response ones):
When I open the request in the chrome debug tools in the network section I can clearly see that the cookies are present, but how can I access those values from my code? I've never worked with cookies before and I don't know what to do to "extract" them... I'm working on a Ionic2 project using Http.
I've read that the allowCredentials: true header has to be sent but that didn't work...
Here's the request/response details:
Here's the service:
public callLogin(service_guid: string, pos_guid: string, login_data: Object) {
return this.http.post(
this.url + service_guid + "/" + pos_guid + "/ack",
login_data,
{withCredentials: true}
)
.map(response => response.headers);
}
And the caller:
this.__posService.callLogin(login_data.service_guid, login_data.pos_guid, {"password": data.password})
.subscribe(
res => {
console.log("Success:");
console.log(res.get("apsession"); // this returns undefined
},
err => {
console.log("Error:");
}
);
When I try to access the cookie from the header it returns undefined. What am I doing wrong here?
The name of the response header you are trying to get is actually Set-Cookie not apsession. So if you did something like res.get("set-cookie") it would return the first header that matched that name. Since you have more than 1, you could do:
let headers: Headers = res.headers;
headers.getAll('set-cookie');
which returns a list of all headers with that name. You could find apsession in there probably.
See:
https://angular.io/docs/ts/latest/api/http/index/Headers-class.html
https://developer.mozilla.org/en-US/docs/Web/API/Response/headers
https://developer.mozilla.org/en-US/docs/Web/API/Headers

How to fetch a wordpress admin page using google apps script?

I need to fetch a page inside my Wordpress blog admin area. The following script:
function fetchAdminPage() {
var url = "http://www.mydomain.invalid/wp/wp-admin/wp-login.php";
var options = {
"method": "post",
"payload": {
"log": "admin",
"pwd": "password",
"wp-submit": "Login",
"redirect_to":"http://www.mydomain.invalid/wp/wp-admin/edit-comments.php",
"testcookie": 1
}
};
var response = UrlFetchApp.fetch(url, options);
...
}
is executed without errors. Anyway, response.getContentText() returns the login page, and I am not able to access the page http://www.mydomain.invalid/wp/wp-admin/edit-comments.php which is the one I want to fetch.
Any idea on how to do this?
There might be an issue with Google Apps Scripts and post-ing to a URL that gives you back a redirection header.
It seems like it might not be possible to follow the redirect with a post - here's a discussion on the issue -
https://issuetracker.google.com/issues/36754794
Would it be possible, if you modify your code to not follow redirects, capture the cookies and then do a second request to your page? I haven't actually used GAS, but here's my best guess from reading the documentation:
function fetchAdminPage() {
var url = "http://www.mydomain.invalid/wp/wp-admin/wp-login.php";
var options = {
"method": "post",
"payload": {
"log": "admin",
"pwd": "password",
"wp-submit": "Login",
"testcookie": 1
},
"followRedirects": false
};
var response = UrlFetchApp.fetch(url, options);
if ( response.getResponseCode() == 200 ) {
// Incorrect user/pass combo
} else if ( response.getResponseCode() == 302 ) {
// Logged-in
var headers = response.getAllHeaders();
if ( typeof headers['Set-Cookie'] !== 'undefined' ) {
// Make sure that we are working with an array of cookies
var cookies = typeof headers['Set-Cookie'] == 'string' ? [ headers['Set-Cookie'] ] : headers['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
// We only need the cookie's value - it might have path, expiry time, etc here
cookies[i] = cookies[i].split( ';' )[0];
};
url = "http://www.mydomain.invalid/wp/wp-admin/edit-comments.php";
options = {
"method": "get",
// Set the cookies so that we appear logged-in
"headers": {
"Cookie": cookies.join(';')
}
};
response = UrlFetchApp.fetch(url, options);
};
};
...
}
You would obviously need to add some debugging and error handling, but it should get you through.
What happens here is that we first post to the log-in form. Assuming that everything goes correctly, that should give us back a response code of 302(Found). If that's the case, we will then process the headers and look specifically for the "Set-Cookie" header. If it's set, we'll get rid of the un-needed stuff and store the cookies values.
Finally we make a new get request to the desired page on the admin( in this case /wp/wp-admin/edit-comments.php ), but this time we attach the "Cookie" header which contains all of the cookies acquired in the previous step.
If everything works as expected, you should get your admin page :)
I would advise on storing the cookies information(in case you're going to make multiple requests to your page) in order to save time, resources and requests.
Again - I haven't actually tested the code, but in theory it should work. Please test it and come back to me with any findings you make.

firebug: "no element found" error when doing a jquery ajax call to an ashx handler

Each of my calls to an ashx handler is causing me to get the "no element found" error in Firefox but my website does not crash when performing calls to that handler. I also get a "HierarchyRequestError:Node cannot be inserted at the specified point in the hierarchy". Below is the code that is giving me those two errors:
$.post("checkout_model.ashx?a=CheckSession", function (data) {
// if session is still available
alert(data);
if ($.trim(data).length > 0) {
$.post("checkout_model.ashx?a=SaveAddress", $("#addressdetails").serialize(), function (data) {
$("#addressresult p.result").remove();
$("#addressresult").prepend(data);
});
storeCookies();
// update orderdetails
$.post("checkout_model.ashx?a=GetCartContent", function (data) {
$("#orderdetails").html(data);
});
var address = $("#AddressLine1").val();
if ($("#AddressLine2").val() != "") address += ", " + $("#AddressLine2").val();
address += ", " + $("#Suburb").val();
$("#tabaddress").text("Step 1: Modify Address: " + address);
$("#accordion").accordion("option", "active", 1);
$("#tabaddress").addClass("modifyaddress");
$("#tabpayment").removeClass("disabled"); // enable step 3
} else {
$("#addressdetails").html("<p class='error'>Your order has timed out. You will need to <a href='viewcart.aspx'>select the items</a> to purchase again.</p>")
}
});
If your ajax response includes a "Content-Type" header with the value "text/xml", Firefox expects the response to be valid XML with a single root element. If it is not, Firefox issues the "no element found" error.
As for the second error, it may be that in either of the following lines the value of "data" is not valid HTML or contains tags like <html> or <body>:
$("#addressresult").prepend(data);
$("#orderdetails").html(data);
Add the responseType request.
var xhr = new XMLHttpRequest();
xhr.open('POST', '...', true);
xhr.responseType = 'json';
See this for more details:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType

Resources