node.js - axios response.data 奇怪的字符

标签 node.js express axios spotify-app

router.get('/spotifyLogin', (req,res) => {
    const state = generateRandomString(16);
    const scope = 'user-read-recently-played';
    const queryParams = querystring.stringify({
        response_type: 'code',
        client_id: client_id,
        scope: scope,
        redirect_uri: redirect_uri,
        state: state
      });
    
    res.redirect(`https://accounts.spotify.com/authorize?${queryParams}`);
});

router.get('/callback', (req,res) => {

    
    const authorizationCode = req.query.code || null;
    const state = req.query.state || null;

    axios({
        method: 'post',
        url: 'https://accounts.spotify.com/api/token',
        data: querystring.stringify({
          grant_type: 'authorization_code',
          code: authorizationCode,
          redirect_uri: redirect_uri,
        }),
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
          Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
        },
      })
        .then(response => {
          if (response.status === 200) {
            res.send(response.data)
        
          } else {
            res.send(response);
          }
        })
        .catch(error => {
          res.send(error);
        });
});

我正在自定义 express api 服务器上执行 spotify 授权代码流 https://developer.spotify.com/documentation/general/guides/authorization/code-flow/

当我向 token url 发出发布请求时,我应该在我的 response.data 中得到一个 json 对象,但我得到了奇怪的字符 Screenshot of response.data

最佳答案

为 axios 请求将 accept-encoding header 设置为 * 为我解决了这个问题。

在您的情况下,应该看起来像这样:

axios({
  method: 'post',
  url: 'https://accounts.spotify.com/api/token',
  data: querystring.stringify({
    grant_type: 'authorization_code',
    code: authorizationCode,
    redirect_uri: redirect_uri,
  }),
  headers: {
    'content-type': 'application/x-www-form-urlencoded',
    Authorization: `Basic ${new Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
    'accept-encoding': '*'
  },
})

关于node.js - axios response.data 奇怪的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74623066/

相关文章:

Node.JS app.get 错误..无法获取/删除/删除/15

node.js - 从 Electron 应用程序中设置服务器

javascript - 出于某种原因不允许我在 Ember js 中导入模块

reactjs - 我应该使用 forceUpdate() 还是寻找另一种方法来重新渲染 React 组件

linux - 在 NodeJS 进程中创建 bash 包装器

javascript - Node.js + Express 路线未按预期工作

node.js - 如何在ejs View 中传递flash消息

node.js - 获取 Node.js npm 命令以在公司代理后面工作

javascript - AngularJS $resource 响应作为字符数组从 ExpressJS 返回

javascript - 当我使用 Jest 从模拟的 axios 调用返回一些响应时变得不确定