【发布时间】:2018-11-28 21:16:43
【问题描述】:
我正在尝试根据 url 值将多个值传递给服务器。
因为我的结果值如下所示
[ { url: 'account/41',
status: '200',
headers:
[ 'content-type = application/json,',
'content-type = application/text' ],
body: [ '{ name: XYZ }' ] },
{ url: 'account/43',
status: '201',
headers: [ 'content-type = application/xml']
body: [ '{ name : ZYX }' ] } ]
在这里,我正在尝试为以上多个值创建服务器请求/响应。我使用 forEach 循环进行迭代,例如 if url = account/41 then body 将返回 [ '{ name: XYZ }' ] },如果 url = account/43 then body 将返回 ['{ name : ZYX }' ]。但它只取结果值的第一个元素并给我以下错误:
UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
我错过了什么但不确定是什么?如何通过正确的输出逐个传递值。
const http = require('http')
const parse = require('./Parse.js')
// create a server object:
let server = http.createServer(function(request, response) {
parse.allFiles().then( results => {
results.forEach(element => {
if (element.url.includes(request.url) ) {
let headerSplit = ( element.headers + '' ).split('=')
let headername = headerSplit[0]
let headerVal = headerSplit[1]
response.setHeader( headername, headerVal )
response.write( JSON.stringify( element.body ) )
response.statuscode = parseInt( element.status )
response.end()
} else {
response.writeHead(404, {'Content-Type': 'text/html'})
response.end('No Page Found')
}
})
})
})
const port = process.env.PORT || 8080
server.listen(port, function() {
// eslint-disable-next-line no-console
console.log('Listening on port ' + port)
})
我有多个文件,其中包含自己的 URL、STATUS、HEADERS 和 BODY。在单个数组中解析这些值(使用 Parse 函数)后,我将进入名为 results 的变量。
[{"url":"account/41","status":"200","headers":["content-type = application/json,"],"body":["{ name: xyz}"]},
{"url":"account/43","status":"201","headers":["content-type = application/xml"],"body":["{ name : zyx}"]}]
如果您遍历结果,您将获得类似 {"url":"account/41","status":"200","headers":["content-type = application/json"] 的元素, "body":["{ name: xyz}"]} 作为响应,如果您将 url 传递给服务器,例如 localhost:8080/account/41 ,它将返回 ["{ name : zyx}"]}] 作为响应身体。
【问题讨论】:
标签: javascript node.js http