bismoney
@bismoney

Как сделать такой запрос в node?

Как переписать данный код на NodeJS?

$file = Yii::getAlias('@frontend') . '/web/files/ya-events/' . $id . '.csv';

        //если файла нет, создаем
        if (!file_exists($file)) {
            $fp = fopen($file, "w"); 
            fwrite($fp, "ClientId,Target,DateTime,Price,Currency\n");
            fwrite($fp, $yaid . ",paid," . time() . "," . $bill->sum . ",RUB\n");
            fclose($fp);
        }

        $authToken = 'ТОКЕН';

        if (function_exists('curl_file_create')) { 
            $cFile = curl_file_create($file, 'text/csv', 'test.csv');
        } else { //
            $cFile = '@' . realpath($file);
        }

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => $cFile]);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Content-type: multipart/form-data; boundary=------------------------" . $authToken,
            'Authorization: OAuth ' . $authToken
        ]);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);

        return $result;

Документация Яндекс: https://yandex.ru/dev/metrika/doc/api2/practice/of...

Я пробую, но получаю ошибку:

string(202) "{"errors":[{"error_type":"invalid_uploading","message":"Не найден параметр запроса.","location":"file"}],"code":400,"message":"Не найден параметр запроса."}"

var dataYandex = '------------------------7zDUQOAIAE9hEWoV\n';
    dataYandex += 'Content-Disposition: form-data; name="file"; filename="data.csv"\n';
    dataYandex += "Content-Type: text/csv\n";
    dataYandex += 'UserId,Target,DateTime,Price,Currency\n';
    dataYandex += data.yandexData[0].ClientId+','+data.yandexData[0].Target+','+data.yandexData[0].DateTime+','+data.yandexData[0].Price+','+data.yandexData[0].Currency+'\n';
    dataYandex += "--------------------------7zDUQOAIAE9hEWoV--";

    let uploadFileForm = new FormData()
    uploadFileForm.append('file', fs.createReadStream(data.file))

    // request options
    var requestOptions = {
        url: data.url,
        method: data.method,
        body: uploadFileForm,
        headers:
            {
                Authorization: 'OAuth Токен',
                'Content-Type': 'multipart/form-data; boundary=--------------------------439864217372737605994368'
            },
    };
  • Вопрос задан
  • 240 просмотров
Пригласить эксперта
Ответы на вопрос 1
rqdkmndh
@rqdkmndh
Web-разработчик
я же вчера уже отвечал на этот вопрос! Ставишь библиотеку axios : npm i axios
и примерно так:
const axios = require('axios'); // или импорт если es6 настроен
    let uploadFileForm = new FormData()
    uploadFileForm.append('file', fs.createReadStream(data.file))

// делаешь запрос
axios.post(data.url, uploadFileForm, { headers: form.getHeaders() })
  .then(function (response) { // смотрим в консоли на результат
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  })
.catch(console.log (error)) // или ошибку

нужно только предварительно в третий параметр headers добавить нужные заголовки Authorization, Content-type и др какие там нужны.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы