How does HTTP POST work in Polymer? - http

I want to know how POST calls work in Polymer. I know that I have to use POST calls for sending sensitive information such as user passwords and access tokens. I tried doing this :
<iron-ajax
id="AjaxPost"
url="/api/login"
method="POST"
content-type="application/x-www-form-urlencoded"
handle-as="json"
on-response="_handleAjaxPostResponse"
on-error="_handleAjaxPostError"
></iron-ajax>
this.$.AjaxPost.params = { email: "abc#gmail.com", password: "password" };
this.$.AjaxPost.generateRequest();
But, this will set the parameters in the URL, which can be viewed in the browser console like :
POST http://localhost:8080/api/login?email=abc%40mgail.com&password=password 400 (Bad Request)
The PUT method allows you to set the data in body, which I think is more secure. Now I have 2 questions :
Can we set the body of POST method too? Or setting params is same as setting body?
If that is possible, how should I extract the data in the server side?
PS: We are not using SSL HTTPS connection. Having said that, which method can be incorporated for better security?

The api document for iron-ajax defines body attribute as below:
body
Object default:
Body content to send with the request, typically used with "POST" requests.
If body is a string it will be sent unmodified.
If Content-Type is set to a value listed below, then the body will be encoded accordingly.
content-type="application/json"
body is encoded like {"foo":"bar baz","x":1}
content-type="application/x-www-form-urlencoded"
body is encoded like foo=bar+baz&x=1
Otherwise the body will be passed to the browser unmodified, and it will handle any encoding (e.g. for FormData, Blob, ArrayBuffer).
To send the data as body, you should modify your request as below
<iron-ajax
id="AjaxPost"
url="/api/login"
method="POST"
content-type="application/json"
handle-as="json"
on-response="_handleAjaxPostResponse"
on-error="_handleAjaxPostError"
></iron-ajax>
this.$.AjaxPost.body = { "email": "abc#gmail.com", "password": "password" };
this.$.AjaxPost.generateRequest();

Related

Is there a way to modify the request body during PACT verification?

I am trying to run a PACT test on the provider side and I don't know how to manipulate the request body that I get from the Pact file. I need to do this because I have to use an id from State step.
In my case, I need to perform a request in State step and afterwards to use the response of that request in the actual Pact verification test. So, I would like to replace a value from the pact file with the one obtained in the State.
Also, for being even more complicated, my body is an XML. So here it is how my pact request looks like:
"request": {
"method": "POST",
"path": "/path/url",
"headers": {
"Content-Type": "application/xml"
},
"body": "<note> <to>John</to> <from>Jane</from> <subject>Reminder</subject> </note>"
}
As I said, in the Provider State I will have a request and the response of this will be let's say 'Mary'. So my question would be how can I replace 'Jane' with 'Mary' in the Pact request body when executing the verification test? Thanks.
I have managed to solve my problem, modifying the request in TargetRequestFilter.
#TargetRequestFilter
public void updateRequest(HttpPost request) {
HttpEntity entity = request.getEntity();
String body = EntityUtils.toString(entity);
body = replace(body, "Jane", "Mary");
entity = new StringEntity(body);
request.setEntity(entity);
}
This piece of code will modify the request right before making the call and will send the desired value instead the one that we have in the Pact file.

http post request to api nativescript vue

Hello I need help with http post request to my server and get response with authentication.
Look on the screens on 1 I use insomnia REST API application. Using this app I got success response with premium days and id.
In second image I got response just from my nativescript vue.js app where I got false response.
There is something wrong with my code. please tell me what.
You are sending a JSON object in your request body from {N} app, on the other hand you are using FormData with your REST client for testing.
You must either change your API to support JSON data on request body which is generally the standard way. In case if you can't do that, then you must use the nativescript-background-http plugin to send FormData. It will be something like,
var params = [
{ name: "username", value: "test" },
{ name: "password", value: "test123" },
{ name: "uuid", value: "xxxx" }
];
var task = session.multipartUpload(params, request);

FCM with Postman - The request was missing an Authentication Key (FCM Token)

//body its like this
{
"to":
"/topics/NEWS"
,
"data":{
"extra_information": "This is some extra information"
},
//notification that i need to give
"notification":{
"title": "ChitChat Group",
"text": "You may have new messages",
"click_action":"ChatActivity"
}
}
The 401 error pertains that your Authorization Key is invalid or incorrect.
When using Postman, add a key= prefix for the value of Authorization, like so:
key=AAA...
See below for a tutorial on Sending Downstream FCM Messages using Postman.
Also, for your notification message payload, text isn't one of the valid parameters, I think you were looking for message instead.
Sending Downstream Messages using Postman
To do this in Postman, you simply have to set the following:
Set request type to POST
In the Headers, set the following:
Content-Type = application/json
Authorization = < Your FCM Server Key > (See your Firebase Console's Cloud Messaging Tab)
Set the payload parameters in the Body (*in this example, we used the raw option, see screenshot (2)*)
Send the request to https://fcm.googleapis.com/fcm/send
Screenshots:
(1)
Note: Always keep your Server Key a secret. Only a portion of my key is visible here so it should be fine.
(2)
(3)
Notice that the request was a success with the message_id in the response.
Wrong:
Authorization:AIzaSyDDk77PRpvfhh......
Correct:
Authorization:key=AIzaSyDDk77PRpvfhh......
Full example:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
While the answers above are still correct, you may choose to use HTTP v1. This requires Bearer instead of key= and uses an Oauth2 access token instead of a server key string. To view HTTP v1 specifications, please refer to the link below:
https://firebase.google.com/docs/cloud-messaging/migrate-v1
I was also getting same error in PHP , solved with below header :
$header = array("authorization: key=" . $this->apiKey . "","content-type: application/json");

Meteor Get request

Bear with me for any mistakes/wrong terminology since I am new to all this. I am using meteor to develop my project and i need to make a get request to an external API. (I already added meteor add http) Below is my code:
HTTP.call( 'GET', 'url', {}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
If i use the code inside my Client folder in Meteor I get the following error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access meteor It has something to do with CORS which I didn't understand how to implement. If I use the code above in my Server side I do get the correct response in the console but how do I use it as a var on my client javascript code?
Tou can use .call function of HTTP and pass your header in options:
HTTP.call(method, url, [options], [asyncCallback])
Arguments
method String
The HTTP method to use, such as "GET", "POST", or "HEAD".
url String
The URL to retrieve.
asyncCallback Function
Optional callback. If passed, the method runs asynchronously, instead of synchronously, and calls asyncCallback. On the client, this callback is required.
Options
content String
String to use as the HTTP request body.
data Object
JSON-able object to stringify and use as the HTTP request body. Overwrites content.
query String
Query string to go in the URL. Overwrites any query string in url.
params Object
Dictionary of request parameters to be encoded and placed in the URL (for GETs) or request body (for POSTs). If content or data is specified, params will always be placed in the URL.
auth String
HTTP basic authentication string of the form "username:password"
headers Object
Dictionary of strings, headers to add to the HTTP request.
timeout Number
Maximum time in milliseconds to wait for the request before failing. There is no timeout by default.
followRedirects Boolean
If true, transparently follow HTTP redirects. Cannot be set to false on the client. Default true.
npmRequestOptions Object
On the server, HTTP.call is implemented by using the npm request module. Any options in this object will be passed directly to the request invocation.
beforeSend Function
On the client, this will be called before the request is sent to allow for more direct manipulation of the underlying XMLHttpRequest object, which will be passed as the first argument. If the callback returns false, the request will be not be send.
Souce: Here
Fixed it. On client side
Meteor.call("getURL",'url',{},function(err,res){
if(err){
console.log('Error: '+err);
}
if(!err){
console.log('Response: '+res);
}
and on server
Meteor.methods({
'getURL': function(url_l){
console.log("Request: "+url_l)
return HTTP.get(url_l)
}
});

Arbitrary response content types in Feathers

I have a custom service that must return data in CSV format.
I can't use a standard Express route, because I need Feathers' hooks on this endpoint.
I couldn't find an example of a Feathers service returning non-HTML, non-JSON data, and have found no way to specify a response content type.
Using res.set('Content-Type', 'text/csv') before returning from the service method didn't work; the final Content-Type header was reset to application/json, even though the method's return value was a regular string.
How can I properly set arbitrary response content types in Feathers' custom service methods?
You can customize the response format like this:
const feathers = require('feathers');
const rest = require('feathers-rest');
const app = feathers();
function restFormatter(req, res) {
res.format({
'text/plain': function() {
res.end(`The Message is: "${res.data.text}"`);
}
});
}
app.configure(rest(restFormatter));
The complete documentation can be found here.
Using your own service specific middleware to send the response should also work.

Resources