html写一个完整网页,贵州灵溪seo整站优化,长沙网站制作一般多少钱,上海网站排名公司序#xff1a; 官方给的node对接火星的demo其实只适用于node开发的web应用#xff0c;但是对于纯node 作为服务端#xff0c;也就是作为webapi来调用#xff0c;你会发现#xff0c;location.host直接是获取不到location的。这个时候#xff0c;其实要单独起个wss的服务的…序 官方给的node对接火星的demo其实只适用于node开发的web应用但是对于纯node 作为服务端也就是作为webapi来调用你会发现location.host直接是获取不到location的。这个时候其实要单独起个wss的服务的关于这点雪狼写了本篇教程 1、博主的nodev18.12.1 2、wsv8.14.1WebSocket 3、CryptoJS4.0.0 正文
1.、来首先我们安装依赖下面两个命令
cnpm install crypto-js4.0.0 -S
cnpm install ws8.14.1 -S
2、引入
import WebSocket from ws;
import CryptoJS from crypto-js
3、写初始化url
function getWebsocketUrl(){return new Promise((resolve, reject) {var apiKey 你的apiKeyvar apiSecret 你的apiSecretvar url wss://spark-api.xf-yun.com/v1.1/chatvar host localhost:8001var date new Date().toGMTString()var algorithm hmac-sha256var headers host date request-linevar signatureOrigin host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1var signatureSha CryptoJS.HmacSHA256(signatureOrigin, apiSecret)var signature CryptoJS.enc.Base64.stringify(signatureSha)var authorizationOrigin api_key${apiKey}, algorithm${algorithm}, headers${headers}, signature${signature}var authorization btoa(authorizationOrigin)url ${url}?authorization${authorization}date${date}host${host}resolve(url)})}
注意这里localhost:8001你直接写8001!后续你调试直接监听这个端口接口
4、开始监听
function wsFun(userSay,callback){getWebsocketUrl().then(url {let ws new WebSocket(url);ws.on(error, console.error);ws.on(open, function open() {var params {header: {app_id:你的app_id,//这里记得替换app_iduid: fd3f47e4-d},parameter: {chat: {domain: general,temperature: 0.5,max_tokens: 1024}},payload: {message: {text: [{role: user,content: userSay}]}}}ws.send(JSON.stringify(params))});ws.on(close, function close() {});ws.on(message, function message(data) {var msgDataJSON.parse(data)if (msgData.header.code ! 0) {callback(提问失败,2)}else{callback(msgData.payload.choices.text[0].content,msgData.header.status)// 这个就是返回啦}});})}
wsFun(你好啊);
5、断点运行代码
$ node --inspect-brk8001 index.js注意这个8001就是咱刚host写的端口 message里面是火星的回复大家可以自行监听并回调
#程序员干货 #人间清醒 #前端回忆录 #争议话题 #程序员圈子热点