nodeJs--url

1.引入模块

const url=require('url');

2.重要API

url.parse(urlStr)

其中两个参数,第一个为url地址,第二个为true则将query解析为对象。

a. url.parse(urlStr, true)

let str='http://www.bing.com:8080/a/b/1.html?a=1&b=2&c=3';
console.log(url.parse(str, true));

 如下query被解析成对象形式: query: { a: '1', b: '2', c: '3' }

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.bing.com:8080',
  port: '8080',
  hostname: 'www.bing.com',
  hash: null,
  search: '?a=1&b=2&c=3',
  query: { a: '1', b: '2', c: '3' },
  pathname: '/a/b/1.html',
  path: '/a/b/1.html?a=1&b=2&c=3',
  href: 'http://www.bing.com:8080/a/b/1.html?a=1&b=2&c=3' 
}

b. url.parse(urlStr)

const url=require('url');

let str='http://www.bing.com:8080/a/b/1.html?a=1&b=2&c=3';
console.log(url.parse(str));

如下query未被解析对象形式: query: 'a=1&b=2&c=3'

Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.bing.com:8080',
  port: '8080',
  hostname: 'www.bing.com',
  hash: null,
  search: '?a=1&b=2&c=3',
  query: 'a=1&b=2&c=3',
  pathname: '/a/b/1.html',
  path: '/a/b/1.html?a=1&b=2&c=3',
  href: 'http://www.bing.com:8080/a/b/1.html?a=1&b=2&c=3' 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Node.js调用OpenAI API的示例代码: ```javascript const fetch = require('node-fetch'); const API_KEY = 'YOUR_API_KEY'; const MODEL_ID = 'davinci'; async function generateText(inputText) { const prompt = inputText.trim(); const url = `https://api.openai.com/v1/models/${MODEL_ID}/completions`; const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${API_KEY}`, }; const body = JSON.stringify({ prompt, max_tokens: 50, n: 1, stop: '\n', }); const response = await fetch(url, { method: 'POST', headers, body }); const data = await response.json(); const text = data.choices[0].text.trim(); return text; } async function main() { const inputText = 'Hello, how are you?'; const outputText = await generateText(inputText); console.log(outputText); } main(); ``` 在上面的示例中,我们首先导入`node-fetch`库,这是一种用于在Node.js中进行HTTP请求的库。然后,我们定义了我们的OpenAI API密钥和模型ID。 接下来,我们定义了一个名为`generateText`的异步函数,该函数将输入文本作为参数,并返回生成的文本。在函数中,我们使用`fetch`函数向OpenAI API发送POST请求。我们使用`headers`对象设置请求头,并将请求体设置为一个JSON字符串。我们将`max_tokens`设置为50,这表示我们想要生成的文本的最大长度为50个标记。我们将`n`设置为1,这表示我们只希望生成一段文本。我们将`stop`设置为`\n`,这表示生成的文本将在第一个换行符处停止。 最后,我们解析API的响应,并从中提取生成的文本。最后,在`main`函数中,我们调用`generateText`函数并打印输出文本。 请注意,此示例代码仅供参考,并且需要您使用自己的OpenAI API密钥和模型ID来运行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值