node调用通义千问乱码问题

本文描述了在使用axios发送阿里云AIGC文本生成API请求时遇到的乱码问题,随后通过对比发现fetch请求返回体自带json解码功能,从而解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


const url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
const apiKey = '';
const axios = require('axios');

const data = {
  model: 'qwen-turbo',
  input: {
    messages: [
      {
        role: 'system',
        content: '你是达摩院的生活助手机器人。',
      },
      {
        role: 'user',
        content: '你好,哪个公园距离我最近?',
      },
    ],
  },
  parameters: {},
};

axios
  .post(url, JSON.stringify(data), {
    headers: {
      Authorization: `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
  })
  .then((response) => {
    // The response data should now be correctly decoded as UTF-8
    console.log(123);
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

这段代码正常返回200状态,但返回体乱码,尝试很多中方法都没有解决。

后来使用fetch发起请求返回正常,对比了一下,猜测是fetch请求返回体自带一个转json的方法,具体搞不懂了


const url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
const apiKey = '';
const data = {
  model: 'qwen-turbo',
  input: {
    messages: [
      {
        role: 'system',
        content: '你是达摩院的生活助手机器人。',
      },
      {
        role: 'user',
        content: '你好,哪个公园距离我最近?',
      },
    ],
  },
  parameters: {},
};

const headers = {
  Authorization: `Bearer ${apiKey}`,
  'Content-Type': 'application/json',
};

fetch(url, {
  method: 'POST',
  headers: headers,
  body: JSON.stringify(data),
})
  .then((response) => response.json())
  .then((responseData) => {
    console.log(responseData);
  })
  .catch((error) => {
    console.error(error);
  });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值