angular2 http post transform . in _ - json

I try to send this json to my php server {"obj":{"r": "hello", "u": "info#email.com", "p": "123abc"}}.
When I send that, my server receives {"obj":{"r": "hello", "u": "info#email_com", "p": "123abc"}}, I don't understand why.
Here is my angular code:
data = {"obj":{"r": "hello", "u": "info#email.com", "p": "123abc"}};
postMethod(data): Observable<any> {
let headers = new Headers();
this.createAuthorizationHeader(headers);
console.log(JSON.stringify(data));
return this._http.post(this.serverUrl, JSON.stringify(data), {headers: headers})
.map((response:Response) => response.json())
.catch(this.handleError);
}

You said you are using a PHP Server.
Even if you are sending a POST request, if you send pure json, you should check over the raw input stream of PHP like:
$stuff = file_get_contents("php://input");
With the data you obtained from this, you can then decode data and then do your things.

Two options:
Don't JSON.stringify the data in the second parameter. Angular will handle the content-type.
Manually set the content-type header to 'application/json'.

Related

I can't resolve error with API POST function

I am trying to post data via an API interface.
I have checked the JSON of the data with JSON formatter and tested the API post in ReqBin and they work fine but when I execute it in App Script I get the same error, seemingly ignoring the attributes I put in the options variable.
Error is
{"code":"not_acceptable","message":"I can only talk JSON. Please set 'Accept' and 'Content-Type' to 'application/json' in your http request header."}
Note: I have tried sending just the data as the payload without json.stringify'ing it as it is formatted as JSON to start with.
In all cases it executes, but comes back 406
Is there another way to add 'Accept':"application/json" into the header??
My Code
function exportNation()
{
// Make a POST request with a JSON payload.
var data = {
"person":
{
"email":"mikenizzckelisaweiner#tv.com",
"last_name":"Bozzrovowski",
"first_name":"Edwzzard",
"tags":"Imported Data,Volunteer,Sign Request"
}
};
var options = {
"method":"POST",
"Content-Type":"application/json",
'Accept':"application/json",
'muteHttpExceptions':true,
'payload':JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://xyz.xyz.com/api/v1/people?
access_token=5604da84fXXXXXXXXXXXXXXXX42da1ea',options );
}
Any help would be greatly appreciated!
Additional HTTP headers need to be sent as a headers object.
See: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#advanced-parameters
var options = {
"method":"POST",
"contentType":"application/json",
"headers": {'Accept':"application/json"},

NodeJS request doesn't encode the entire form

The task is rather simple, I request the endpoint with POST request (https://banana.com/endpoint/swap.php), give it my form: { banana: ["China's Red", "Sweden's Gray"], apples: [] } and send it.
However, the Request module for NodeJS that I am using does not encode the empty array (in this case "apples") and if the endpoint doesn't receive the "apples" array, it returns an error - "Invalid JSON". I have tried doing this with already encoded strings and it works just fine. I am also unable to stringify my json and then use encodeURI(), as it will then give "bananas" and "apples" quotes around them, which will get encoded - needless to say, the endpoint doesn't like that either.
I'd really appreciate if somebody could at least point me in the right direction. As I am unsure on how to proceed with this, without creating some awful spaghetti code.
data = { banana: ["China's Red", "Sweden's Gray"], apples: [] }
result = JSON.parse(JSON.stringify(data)) .
You wouldn't get double around banana and apple and if you need to access then access it
console.log(result.banana)
console.log(result.apple)
So if you need to feed this result in post request then -
url = 'your url';
const options = {
url: url,
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-Charset': 'utf-8'
},
json: result
};
request.post(options, function (err, response, body) {
// do something with your data
})
Let me know if this works.

Unable to Print a JSON Object in Node js with "content-type": "text/plain; charset=UTF-8"

I am trying to print JSON object i.e. req.body in NodeJS using the below commands, but using JSON.stringify doesn't help. Could someone please suggest/guide how I can print this JSON object req.body
console.log("printing body: "+JSON.stringify(req.body))
console.log("printing body: "+req.body)
console.log("printing headers: "+JSON.stringify(req.headers))
Output:
printing body: {}
printing body: [object Object]
printing headers: {
"x-amz-sns-message-type": "SubscriptionConfirmation",
"x-amz-sns-message-id": "3dd623ert-7203-4e12-bf11-36589f9dce65",
"x-amz-sns-topic-arn": "arn:aws:sns:us-west-2:33030356879323:testTopic10",
"content-length": "1520",
"content-type": "text/plain; charset=UTF-8",
"host": "example.com",
"connection": "Keep-Alive",
"user-agent": "Amazon Simple Notification Service Agent",
"accept-encoding": "gzip,deflate"
}
Guidelines to Parse the JSON Object given by Amazon SNS:
In step 1: Point 2 of this document it advises
Use a JSON parser that handles converting the escaped representation
of control characters back to their ASCII character values (for
example, converting \n to a newline character). You can use an
existing JSON parser such as the Jackson JSON Processor
(http://wiki.fasterxml.com/JacksonHome) or write your own.
EDIT 1:
As you may see the printed headers, they have content-type": "text/plain; charset=UTF-8, could this be the reason why the bodyparser.json() doesn't work and we are unable to use JSON.stringify()
EDIT 2
Here is my body parsing code.
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // Used to parse the JSON request
app.use(bodyParser.urlencoded({ extended: true }));
EDIT 3:
SAMPLE OF THE RAW BODY THAT IS SENT IN THE REQUEST
{
"Type" : "SubscriptionConfirmation",
"MessageId" : "4c3232a-f297-4fba-96e8-dc821a0b2621",
"Token" : "2336412f37fb687f5d51e6e241d59b68c4e23a8e1a7b89aecf0dd7e227b0cf8ce107c9d1a4216d1aaf7dcdf66c18f0e06f1811a98351ced5018395453fee6f7e12fd5962220e0a81431063914e7b8d0c5340baeaf9dd2fe12e5288fbb88405fca2136c026d2b04e709e8ab6",
"TopicArn" : "arn:aws:sns:us-west-2:3303035234123:testTopic10",
"Message" : "You have chosen to subscribe to the topic arn:aws:sns:us-west-2:33030123453:testTopic10.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
"SubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:us-west-2:33030234243413:testTopic10&Token=2336412f37fb687f5d51e6e241d59b68c4e58148956199a8e1a7be0dd7e227b0cfer1aaf7dcdf66c18f0e06f1811a98351ced5018395453fee6f7e12fd5962220e0a81431063914e7b8d0c5340baeaf9dd2fe12e5288fbb88405fca2136c026d2b04e709e8ab6",
"Timestamp" : "2017-09-04T13:06:36.005Z",
"SignatureVersion" : "1",
"Signature" : "QRy9574PIfSuNReyGEgDO86/utgF7R5enCmQTYBsUIdN0ohF9jWzh+qU9FLDp7EIXzg6Q3bLoI3HeYzNE4iMLHATixf2Iz29e0/ekWaMBewj+Q+pt42tKDh9YndRmyE2CSRJ7LTnvTVpS3MUgDI/kaQKmThxgN9wb8y8gebojuIE6zNAbYmuVVA+W6rIiF+dyG9e+f89dWSSReITB19XaVtLZ/BrcQWRyrBRFE06lXxYuGaLUIfTvItleaxX/BxKnNdxUL04sRNQ==",
"SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-433026a4050d206028891123453da859041.pem"
}
JSON.stringify() did print out the object. The object is just empty, i.e {}.

Get JSON in POST in kemal

What I want is a POST request in kemal where the body has a certain number of keys/values that I want to access and then an arbitrary JSON Object that I just want to stringify and pass on and later parse back to JSON.
My problem is that I apparently can't get the types right.
Think of a potential JSON body like this:
{
"endpoint": "http://example.com",
"interval": 500,
"payload": {
"something": "else",
"more": {
"embedded": 1
}
}
}
Now what I've been trying to do is the following:
require "kemal"
post "/schedule" do |env|
endpoint = env.params.json["endpoint"].as(String)
interval = env.params.json["interval"].as(Int64)
payload = String.from_json(env.params.json["payload"].as(JSON::Any))
# ... move things along
env.response.content_type = "application/json"
{ id: id }.to_json
end
Kemal.run
Now apparently what I seem to be getting when accessing "payload" is something of type Hash(String, JSON::Type), which confuses me a bit.
Any ideas how I'd be able to just get a sub-JSON from the request body, transform it to String and back to JSON?
Updated: payload is a type of JSON::Type. Casting and then calling .to_json does the trick.
require "kemal"
post "/schedule" do |env|
endpoint = env.params.json["endpoint"].as(String)
interval = env.params.json["interval"].as(Int64)
payload = env.params.json["payload"].as(JSON::Type)
env.response.content_type = "application/json"
payload.to_json
end
Kemal.run

Laravel 4 & Mandrill JSON response

I've started sending mails through Laravel (4.2) and its embedded Mandrill driver these days, but I need to catch Mandrill's response somehow.
Here's the code I use to send the message:
Mail::queue('emails.customerspromo', array('messaggio'=>$content, 'disclaimer'=>$disclaimer, 'user_email'=>$to, 'user_id'=>$uid), function($message) use ($sender, $to, $subject) {
$message->from('my#address.it', $sender);
$message->to($to);
$message->subject($subject);
$message->setCharset('UTF-8');
$message->getHeaders()->addTextHeader('X-MC-GoogleAnalytics', 'www.my-site.it');
$message->getHeaders()->addTextHeader('X-MC-GoogleAnalyticsCampaign', 'my-campaign');
});
What I need to intercept is Mandrill's JSON response, for example:
[
{
"email": "destination#address.com",
"status": "sent",
"_id": "80e1ca49d3ed4cbb9d9a3d932c0a14f8",
"reject_reason": null
}
]
How can I do that using Laravel's integrated drivers for Mandrill?
I could use Mail::send instead of Mail::queue, if it's necessary to interpret the response in real time.
Put a variable before your mail function like this:
$response = Mail::queue('emails.customerspromo', array('messaggio'=>$content, 'disclaimer'=>$disclaimer, 'user_email'=>$to, 'user_id'=>$uid), function($message) use ($sender, $to, $subject) {
$message->from('my#address.it', $sender);
$message->to($to);
$message->subject($subject);
$message->setCharset('UTF-8');
$message->getHeaders()->addTextHeader('X-MC-GoogleAnalytics', 'www.my-site.it');
$message->getHeaders()->addTextHeader('X-MC-GoogleAnalyticsCampaign', 'my-campaign');
});
It will still work but now you can see the response from mandrill.