Запрос метода GET для получения изображений работает в локальной, но не в тестовой / производственной среде, что я должен учитывать в реальных условиях? - PullRequest
0 голосов
/ 20 июня 2019

Я использую API для получения URL-адреса источника изображения и отправляю метод request.get (...) для получения изображения и отправки его на загрузку S3. В локальной среде он отлично работает, но в реальной среде при загрузке на S3 возвращается изображение с 0 байтами.

Я пытался выяснить, была ли это проблема с конфигурацией CORS после метода S3 post, но никаких изменений не произошло.

Загрузка изображения из локальной сети и в режиме реального времени по общей ссылке на изображения Google, та же проблема, что и при локальной настройке, но размеры файлов в реальной среде составляют 0 байт.

Попытка использования промежуточного программного обеспечения Express Cors для конкретного маршрута, без изменений.

function sendUrlImageToS3 (uri, filename) {
  return new Promise(function (resolve, reject) {
    const subFolder = 'uploads/';
    const s3Auth = new aws.S3({ params: {
      Bucket: `BUCKET_NAME`,
      Key: `RANDOM_KEY_STRING`
    }})
    // Send a GET request to the uri provided, initiate retrieval of the response data object
    // Send that as a body of the s3.upload and configure as public read
    // Once confirmed, return promise as resolved or rejected
    request.get(uri)
      .on('response', (res) => {
        if (res.statusCode === 200) {
          s3Auth.upload({ Body: res, ACL: "public-read", CacheControl: '5184000'}, (err, data) => {
            if (err) {
              reject({ success: false, error: err, data: null });
            }
            resolve({ success: true, error: false, data });
          })
        }
      })
  });

// This is called like this...
sendUrlImageToS3(IMAGE_URL_STRING, RANDOM_STRING_NAME);

In the local environment, it sends the image to S3 bucket which is the same as the testing environment. When local environment loads it, I would expect it to be the same with the testing environment given that the bucket is the same. However, the upload from testing environment is a 0byte object.

I believe I have safely ruled out that the upload to S3 is not the issue, but rather the request.get(...) result. I logged out the result from the request in local and live and the rawHeader is (***'d the spot that was different between live and local):

// rawHeaders: 
    // [ 'Content-Type',
    //   'image/jpeg',
    //   'Cache-Control',
    //   'public,max-age=315360001',
    //   'X-Imgix-Content-DPR',
    //   '1',
    //   'X-Content-Type-Options',
    //   'nosniff',
    //   'Last-Modified',
    //   'Thu, 20 Jun 2019 2:50:45 GMT',
    //   'X-Imgix-Render-ID',
    //   '000000006D424E84',
    //   'Server',
    //   'imgix-fe',
    //   'Access-Control-Allow-Methods',
    //   'GET',
    //   'Access-Control-Allow-Origin',
    //   '*',
    //   'Content-Length',
    //   '71879',
    //   'Accept-Ranges',
    //   'bytes',
    //   'Date',
    //   'Thu, 20 Jun 2019 02:50:45 GMT',
    //   'Via',
    //   '1.1 varnish',
    //   'Age',
    //   '0',
    //   'Connection',
    //   'close',
    //   'X-Served-By',
    //   'cache-dca17761-DCA',
    //   'X-Cache',
    //   'MISS',
    //   'X-Cache-Hits',
    //   '0', <<< ***THIS ONE HERE IS 0, BUT IN LOCAL ENVIRONMENT SHOWS A BYTE SIZE SUCH AS '4015'
    //   'X-Timer',
    //   'S1560999046.569615,VS0,VE408' ],

1 Ответ

0 голосов
/ 24 июня 2019
 const options = {
  url: uri,
  headers: {
      'User-Agent': req.headers['user-agent']
  },
  encoding: null // required, ensures that the data returning from get request is not encoded
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    s3Auth.upload({ Body: body, ACL: "public-read", CacheControl: '5184000'}, (err, data) => {
      if (err) {
        reject({ success: false, error: err, data: null });
      }
      resolve({ success: true, error: false, data });
    })
  } else {
    reject({ success: false, error: err, data: null });
  }
});

Нашел ответ для всех, кто может столкнуться с этим. Опции должны быть переданы в запрос с информацией агента пользователя (кажется, что API, из которого я звоню, ищет эту проверку, но не уверен) и кодировка: null.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...