// 服务器端
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>
客户端运行在 vs code
自带的 127.0.0.1:5500
上 , 用ajax
的jsonp
跨域访问 http://localhost:3000
, 为什么拿不到 request
中 url
的 协议
, 域名
和 端口号
等信息
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 地址。见下面的文档
如果想得到主机名和端口号,请从请求头信息里获取。至于协议,因为你引用的 http 模块,当然是 http 协议的请求了,如果你引用 https 模块,则请求就是 https 协议了。因为协议不对,请求收不到啊。