序:
官方给的node对接火星的demo其实只适用于node开发的web应用,但是对于纯node 作为服务端,也就是作为webapi来调用,你会发现,location.host直接是获取不到location的。这个时候,其实要单独起个wss的服务的,关于这点,雪狼写了本篇教程,
1、博主的node:v18.12.1
2、ws:v8.14.1(WebSocket)
3、CryptoJS:4.0.0
4、有小伙伴反馈,message返回提示401的报错!到公众号:“ 程序员野区 ” 回复“科大讯飞401报错”,会返回解决方案。
正文:
1.、来首先我们安装依赖,下面两个命令
cnpm install crypto-js@4.0.0 -S
cnpm install ws@8.14.1 -S
2、引入
import WebSocket from "ws";
import CryptoJS from 'crypto-js'
3、写初始化url
function getWebsocketUrl(){
return new Promise((resolve, reject) => {
var apiKey = "你的apiKey"
var apiSecret = "你的apiSecret"
var url = 'wss://spark-api.xf-yun.com/v1.1/chat'
var host = "localhost:8001"
var date = new Date().toGMTString()
var algorithm = 'hmac-sha256'
var headers = 'host date request-line'
var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`
var 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、开始监听
注意下面那个app_id要替换成你直接的app_id
function wsFun(userSay,callback){
callback=callback||function(){};
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_id
"uid": "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 msgData=JSON.parse(data)
if (msgData.header.code !== 0) {
callback("提问失败",2)
}else{
callback(msgData.payload.choices.text[0].content,msgData.header.status)// 这个就是返回啦
}
});
})
}
wsFun("你好啊");
5、断点运行代码
$ node --inspect-brk=8001 index.js
注意,这个8001就是咱刚host写的端口, message里面是火星的回复,大家可以自行监听并回调
注意!!!!!有小伙伴反馈,message返回提示401的报错!到公众号:“ 程序员野区 ” 回复“科大讯飞401报错”,会返回解决方案。