B
B
bismoney2022-03-29 13:30:02
Node.js
bismoney, 2022-03-29 13:30:02

How to make such request in node?

How to rewrite this code in 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;

Yandex documentation: https://yandex.ru/dev/metrika/doc/api2/practice/of...

I try, but I get an error:

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'
            },
    };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Goretsky, 2022-03-30
@rqdkmndh

I already answered this question yesterday! You install the axios library : npm i axios
and something like this:

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)) // или ошибку

you only need to first add the necessary headers Authorization, Content-type, etc. to the third headers parameter, which are needed there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question