0

我正在尝试在我的代码中进行 axios 调用以获取 csv 文件并将其转换为 JSON。当代码独立时,我能够正确地进行调用和转换,但是当我将其更改为从外部源作为函数调用时,执行 axios 调用时出现错误代码 400,但随后我无论如何都会得到状态为 200 的正确响应。这是我作为测试执行的代码:

console.log('Test1');
getCSVUsers(usersurl, user, pass, CSVdelimiter)
    .then((usersjson) => {
        console.log(usersjson.users[0]);
    })

以及函数的定义:

//Dependencies
import axios from 'axios';
import csv from 'csvtojson';

const getCSVUsers = (url,user,pass,delimiter) => {
  console.log('Test3')
  return new Promise((resolve, reject) => {
    console.log('Test4');
    let users = {}; //Creating JSON structure
    users.users = []; //Creating required array in users JSON.

    const options = { //Creating GET call credentials requirements
        method: 'post',
        headers: {
          'Authorization': 'Basic '+Buffer.from(`${user}:${pass}`).toString('base64')
        }
      }
      console.log('Test5');
        //Make API get call
        axios.get(url, options) //Making the call
        .then(response => { //Getting the response
          console.log('response.status'); 
          csv({ 
            delimiter: delimiter, //Defining the CSV delimiter
            trim:true
          })
            .fromString(response.data) //Processing CSV from response
            .then(function(jsonArrayObj){ //putting result in object
              users.users = jsonArrayObj; //putting object in json array
              resolve(users);
            })
        }).catch((err) => {
          console.log('TestErr');
          console.error(err);
        });
  });
}

export {getCSVUsers}

控制台返回以下内容:

Test1
Test3
Test4
Test5
Response Error:Error: Request failed with status code 400
200
{User1 stats are returned correctly}

我尝试使函数异步并添加“等待”,但这也没有解决问题。

4

0 回答 0