**更新:**增加了完整的服务器代码。注意静态内容的路由工作正常,只有相对于Dat的路由失败。另外,我运行的是节点10.8.0
,没有transpiler或任何东西,服务器是用micro -l tcp://0.0.0.0:$PORT
运行的
我正在尝试使用Zeit micro
运行dat-node
。我有此微服务
const { send } = require('micro')
const Dat = require('dat-node')
const handler = require('serve-handler')
const { router, get, post } = require('microrouter')
const static = async (request, response) => {
await handler(request, response, {
// static app folder
public: 'static',
// javascript header for es modules
headers: {
source: '**/*.mjs',
headers: [{
key: 'Content-Type',
value: 'text/javascript'
}]
},
// no directory listing
directoryListing: false
})
}
const createGame = (request, response) => {
Dat('./game', (err, dat) => {
if (err) throw err
let progress = dat.importFiles({watch: true})
progress.on('put', function (src, dest) {
console.log('Importing ', src.name, ' into archive')
})
dat.joinNetwork()
send(response, 200, { key: dat.key.toString('hex') })
})
}
const joinGame = (request, response) => {
}
module.exports = router(
post('/game', createGame),
post('/game/:game', joinGame),
get('/*', static)
)
我只想创建一个dat归档并返回公钥,但当我调用send
时,我得到了这个错误
(node:2054) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:469:11)
at send (/home/ubuntu/workspace/node_modules/micro/lib/index.js:72:8)
at Dat (/home/ubuntu/workspace/index.js:35:5)
at /home/ubuntu/workspace/node_modules/dat-node/index.js:112:9
at apply (/home/ubuntu/workspace/node_modules/thunky/index.js:44:12)
at process._tickCallback (internal/process/next_tick.js:63:19)(node:2054) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)(node:2054) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
所以,我不确定头被发送到哪里,也许我只是以错误的方式处理Dat回调-不知道如何实现此服务。
2条答案
按热度按时间0sgqnhkj1#
问题似乎是
micro
的使用,而不是dat-node
的任何问题。当你在micro中进行异步工作时,你需要使用Javascript的async/await
工具(promises)。以下是固定代码:
ego6inou2#
如果你导出了这个函数,这个代码段就可以工作了。用
micro whatever.js
和curl运行到localhost:3000,它应该会返回这个键。