I am trying to get the body of an Amazon SNS request but it is returned as an object. I can get the headers from the request without any problems. (req.header('x-amz-sns-message-type'))
var msgBody = req.body.Message;
The msgBody variable is returned as an object where I expect to get the string value from the request.
I am using express and body-parser with the following options:
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));
The request format is as follows (shortened for easy reading):
POST /createLog/slackLogSNS/ HTTP/1.1 x-amz-sns-message-type: Notification x-amz-sns-message-id: 3f71e0db-a9b1-5092-96f4-b26015676ba0 { "Type" : "Notification", "MessageId" : "3f71e0db-a9b1-5092-96f4-b26015676ba0", "TopicArn" : "arn:aws:sns:us-east-2:043886476179:testslackSNS", "Subject" : "hghghgfhgfhg", "Message" : "{\n \"Type\" : \"Notification\",\n \"MessageId\" : \"22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324\",\n \"TopicArn\" : \"arn:aws:sns:us-west-2:123456789012:MyTopic\",\n \"Subject\" : \"My First Message\",\n \"Message\" : \"Hello world!\",\n \"Timestamp\" : \"2012-05-02T00:54:06.655Z\",\n \"SignatureVersion\" : \"1\",\n \"Signature\" : \"EXAMPLEw6JRNwm1LFQL4ICB0bnXrdB8ClRMTQFGBqwLpGbM78tJ4etTwC5zU7O3tS6tGpey3ejedNdOJ+1fkIp9F2/LmNVKb5aFlYq+9rk9ZiPph5YlLmWsDcyC5T+Sy9/umic5S0UQc2PEtgdpVBahwNOdMW4JPwk0kAJJztnc=\",\n \"SigningCertURL\" : \"https://sns.us-west-2.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem\",\n \"UnsubscribeURL\" : \"https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96\"\n}", } }
2 Answers
Answers 1
console.log("stringified json")
will parse the JSON string before printing it to the console. However if you check the typeof req.body.Message
you'll see it as string type as expected.
console.log(typeof req.body.Message)
It's the console.log() method doing the conversion behind the seen.
if you need you could use JSON.stringify({your json object})
to get a stringified version of the objects.
Below is the code(index.js) to simulate your case with the provided request payload in the question.
const express = require('express') const bodyParser = require('body-parser') const app = express() app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing app.post('/', function(req, res) { // get posts console.log(req.body); var x = req.body.Message; console.log(typeof req.body.Message) // string console.log(x.Type) // undefined res.json({"a" : "test response"}) }); app.listen(3000, () => console.log('Example app listening on port 3000!'))
Answers 2
The "Message" that you are looking for is part of the stringified JSON in your request.
You should be able to access it using...
const msgBody = JSON.parse(req.body.Message).Message;
0 comments:
Post a Comment