我正在尝试向我的服务器发送/发布请求,该服务器使用Hapi.js提供数据(保存到db(knex))。
除了post请求之外,我正在尝试使用2个函数将随机数转换为十六进制字符串并将其设置为我的数据对象中的hexString键。
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
}
})
}
}
帖子卷曲命令:
curl http://localhost:8000/ -d "uri: 'this is the uri' payload: { jsonObj: 'enter payload info here'}"
Post Curl命令返回的内容:
{"id":"87c467dd-3703-4f9f-a1ac-78551dc33109","timeOut":null}
当我在console.log()时返回数据对象:
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
感谢任何输入〜
答案 0 :(得分:0)
我发现了为什么它没有发布数据。 我的卷曲命令错了。
这是一个正确的curl命令:
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)
}