📜  节点 | URL.resolve(from,to) API(1)

📅  最后修改于: 2023-12-03 15:41:25.507000             🧑  作者: Mango

Node.js | URL.resolve(from,to) API

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that executes JavaScript code outside a web browser. One of the built-in Node.js modules is the URL module which contains methods for URL resolution and parsing.

The URL.resolve() method is used to resolve a target URL relative to a base URL. It takes two arguments: the first argument is the base URL, and the second argument is the target URL. The method returns a new URL string with the target URL resolved relative to the base URL.

Syntax
URL.resolve(from, to)
Parameters
  • from - The base URL to resolve against. It can be a string, a URL object or an instance of the URLSearchParams class.
  • to - The target URL to resolve. It can be a string or a URL object.
Return Value

The URL.resolve() method returns a new string that represents the resolved URL.

Example Usage
const { URL } = require('url');

const base = 'https://www.example.com/products';
const target = '/shoes/nike';
const resolved = URL.resolve(base, target);

console.log(resolved);
// Output: https://www.example.com/shoes/nike

In this example, we first import the URL module and create a base URL string https://www.example.com/products. We also define a target URL string '/shoes/nike'. We then call the URL.resolve() method with the base URL and target URL as arguments. The method resolves the target URL relative to the base URL and returns a new URL string https://www.example.com/shoes/nike. Finally, we log the resolved URL to the console.

Conclusion

The URL.resolve() method is a convenient function from the URL module to resolve a target URL relative to a base URL. It is widely used in Node.js applications for URL manipulation and can be used to build more complex URL manipulation functions.