Ras*_*uls 33 javascript url node.js
require('url').parse('someurl.com/page')已弃用仅文档,并且我们严格的 linter 对此不满意......我试图在我们的代码中用互联网建议的new URL('someurl.com/page')内容替换它,这在大多数情况下有效。
但是,我们有一些示例,其中 url 是本地图像,some/image.png并且与 url.parse() 配合良好并返回:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/some/image.png',
path: '/some/image.png',
href: '/some/image.png'
}
Run Code Online (Sandbox Code Playgroud)
但是建议的替换new URL('some/image.png')会引发类型错误...
类型错误 [ERR_INVALID_URL] [ERR_INVALID_URL]:无效的 URL:/some/image.png
url.parse 正在做一些验证并接受本地路径,但新的 url 构造函数没有。该怎么办 ?
Sau*_*try 20
const server = http.createServer((req, res) => {
const baseURL = req.protocol + '://' + req.headers.host + '/';
const reqUrl = new URL(req.url,baseURL);
console.log(reqUrl);
});
Run Code Online (Sandbox Code Playgroud)
会给 reqUrl :
URL {
href: 'http://127.0.0.1:3000/favicon.ico',
origin: 'http://127.0.0.1:3000',
protocol: 'http:',
username: '',
password: '',
host: '127.0.0.1:3000',
hostname: '127.0.0.1',
port: '3000',
pathname: '/favicon.ico',
search: '',
searchParams: URLSearchParams {},
hash: ''
}
Run Code Online (Sandbox Code Playgroud)
小智 12
您可以使用 URL 构造函数的 base 参数。例如:
new URL('some/image-png', "https://dummyurl.com")
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请访问 https://nodejs.org/api/url.html#url_constructor_new_url_input_base。
const http = require("http");
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}/`);
const query = new URLSearchParams(url.search);
console.log(query.entries());
res.end("I am done");
});
server.listen(3000);
Run Code Online (Sandbox Code Playgroud)
const path = require("path");
const url = require("url");
const p = path.join("public", "images", "a.jpg");
console.log(p); // public\images\a.jpg
console.log(new url.URL(p, "http://xxx").pathname); // /public/images/a.jpg
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21953 次 |
| 最近记录: |