鍍金池/ 問答/HTML/ http.createServer里request解析不出完整的url ?

http.createServer里request解析不出完整的url ?

// 服務(wù)器端
require('http').createServer((req,res)=> {
    const urlObj = url.parse(req.url, true)
    console.log(urlObj)
    // ... jsonp處理
}).listen(3000)
<!-- 客戶端 -->
<!-- 127.0.0.1:5500 -->
<script>
    $.ajax({
        url: 'http://localhost:3000',
        dataType: 'jsonp',
        jsonp: 'jsonp',
        success: function(data) {
            console.log(data)
        },
        error: function(err) {
            console.log(err)
        }
    })
</script>

客戶端運(yùn)行在 vs code 自帶的 127.0.0.1:5500 上 , 用ajax
jsonp 跨域訪問 http://localhost:3000 , 為什么拿不到 requesturl協(xié)議 , 域名端口號 等信息

Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?jsonp=jQuery32106407836705105261_1510132595282&_=1510132595283',
  query:
   { jsonp: 'jQuery32106407836705105261_1510132595282',
     _: '1510132595283' },
  pathname: '/',
  path: '/?jsonp=jQuery32106407836705105261_1510132595282&_=1510132595283',
  href: '/?jsonp=jQuery32106407836705105261_1510132595282&_=1510132595283' }
回答
編輯回答
咕嚕嚕

url 確實解析不出來,因為 req.url 是請求頭里的 url 地址。見下面的文檔

王頂,node.js,408542507@qq.com

如果想得到主機(jī)名和端口號,請從請求頭信息里獲取。至于協(xié)議,因為你引用的 http 模塊,當(dāng)然是 http 協(xié)議的請求了,如果你引用 https 模塊,則請求就是 https 協(xié)議了。因為協(xié)議不對,請求收不到啊。

require('http').createServer((req,res)=> {
    console.log(req.headers.host);   // 這里可以得到主機(jī)名和端口號
    const urlObj = url.parse(req.url, true)
    console.log(urlObj)
    // ... jsonp處理
}).listen(3000)
2018年8月15日 08:36