首页 > 解决方案 > request.path 在节点 10 中未定义

问题描述

根据节点文档,request.path应该存在,但它不在节点上v10.13.0

const  http = require('http')

require('../src/shared/globals.js')

const port = 4000

const host = '127.0.0.1'

const server = http.createServer(function(request, response) {
  log(`>>>> url ${request.url}`)
  log(`>>>> path ${request.path}`)
})

module.exports = async function() {
  server.listen(port, host, function() {
    console.log(`Web hook server listening at http://${host}:${port}`)
  })
}

将返回:

  >>>> url /
  >>>> path undefined

为什么 request.path 未定义?

标签: node.jshttp

解决方案


它包含在文档中,但位于“ClientRequest”部分下。我的理解是当你想调用服务器时使用它。它是未定义的,因为回调中的“请求”不是 ClientRequest。

您可以使用 url 模块来解析您获得的“request.url”。这是一个示例https://www.codeexpedia.com/node-js/node-js-http-request-url-param-path-and-body/

编辑:这里有一些有用的链接。

Node.jsurl.parse()链接:https ://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost

Node.js 客户端请求文档:https ://nodejs.org/api/http.html#http_class_http_clientrequest

Node.jsrequest.path文档:https ://nodejs.org/api/http.html#http_request_path


推荐阅读