essxiv essxiv - 2 months ago 14
Node.js Question

/post request containing data using request.payload (hapi.js)

I'm trying to do a /post request to my server that gives data (saves to db (knex)) using Hapi.js.

Along with the post request, i'm trying to use 2 functions that will turn a random number into a hex string and set it to the hexString key in my data object.

routes.js

module.exports.postData = {
method: 'POST',
path: '/',
handler: (request, reply) => {
const post = request.payload
const data = {
id: uuid.v4(),
timeOut: null,
uri: post.uri,
payload: post.payload,
hexString: undefined
}
store.link.createRandomInt()
.then((randomNum) => {
store.link.createHexString(randomNum)
.then((hex) => {
data.hexString = hex
reply(store.link.createLink(data)).code(201)
})
})
}
}


functions.js

module.exports.createRandomInt = function () {
return new Promise(function (resolve, reject) {
var randomNumber = Math.floor((Math.random() * 100000000))
resolve(randomNumber)
})
}

module.exports.createHexString = function (int) {
return new Promise(function (resolve, reject) {
var hexString = int.toString(32)
resolve(hexString)
})
}


dbFunctions.js

module.exports = {
createLink: function (link) {
return db('links').insert(link)
.then((id) => {
return {
id: uuid.v4(),
timeOut: null,
uri: link.uri,
payload: link.payload,
hexString: link.hexString
}
})
}
}


Post Curl Command:

curl http://localhost:8000/ -d "uri: 'this is the uri' payload: { jsonObj: 'enter payload info here'}"


What Post Curl Command Returns:

{"id":"87c467dd-3703-4f9f-a1ac-78551dc33109","timeOut":null}


When I console.log() the returned data object:

Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }


Thanks for any input~

Answer

I found out why it wasn't posting data. My curl command was wrong.

Here would be a correct curl command:

curl -H "Content-Type: application/json" -X POST -d '{"uri": "this uri", "payload": "enter payload info here"}' http://localhost:8000/

routes.js

handler: (request, reply) => {
    const post = request.payload
    const key = store.util.createRandomInt()
    const data = {
      id: uuid.v4(),
      timeOut: null,
      uri: post.uri,
      payload: post.payload,
      key: key,
      hexString: store.util.convertToHexString(key)
    }
    const result = store.sqlStore.createLink(data)
    reply(result).code(201)
}