Error could not handle the request как исправить

I feel like pulling my hair out; this is either super simple and i'm having brain freeze or it is not that simple. What I want I am trying to unshorten a shortened URL using firebase, when a user...

You are seeing Error: could not handle the request since there probably was an exception and it timed out.

Check your logs using:

firebase functions:log

Refer docs for more details

Here’s how I got URL unshortening to work

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const http = require('http');
const urlP = require('url');

const unshorten = (url, cb) => {
  const _r = http.request(
    Object.assign(
      {},
      urlP.parse(url),
      {
        method: 'HEAD',
      }
    ),
    function(response) {
      cb(null, response.headers.location || url);
    }
  );
  _r.on('error', cb);
  _r.end();
};

const resolveShortUrl = (uri, cb) => {
  unshorten(uri, (err, longUrl) => {
    if (longUrl === uri) {
      cb(null, longUrl);
    } else {
      resolveShortUrl(longUrl, cb);
    }
  });
};

exports.url = functions.https.onRequest((requested, response) => {
  var uri = requested.query.url;
  resolveShortUrl(uri, (err, url) => {
    if (err) {
      // handle err
    } else {
      response.send({ url });
    }
  });
});

You can follow the hello world example straight away and use the above code as your function.

Above code uses HEAD requests to peek into ‘Location` field of the headers and decides if the url can be further unshortened.

This is lighter as HEAD requests ask for no body (thereby avoiding body parsing). Also, no third party lib required!

Also note that the url passed as a query param. So the request would be

http://<your_firebase_server>/url?url=<short_url>

Saves you the trouble of URL re-writes. Plus semantically makes a little more sense.

@montanaflynn

Getting this plain text response every 30 or so requests:

Error: could not handle the request

Checking the server logs I found this:

severity:  "ERROR"  
textPayload:  "Error: function crashed out of request scope
 Function invocation was interrupted.
" 

@iangudger

There are no known issues that would cause this. Are you sure that it isn’t a bug in your app?

@montanaflynn

I never get the error when testing with (make test) or making the handler from the golang net/http server. I did find a similar issue: firebase/functions-samples#78 but that’s for javascript.

My handler encodes a png image and writes it to http.ResponseWriter, here’s the entire app.

Here is more error information from the logs:

Function execution took 284 ms, finished with status: 'connection error'

@iangudger

Can you try removing the use of the nodego logger and see if that fixes the problem?

By the way, when you add the logging back, you should add the nodego.WithLoggerFunc middleware. That way your logs will get associated with the request that triggered them. See examples/logging.go.

@montanaflynn

Removing the nodego logger does seem to fix the issue.

The problem remains even when using the nodego.WithLoggerFunc middleware. When using the middleware should I not use nodego.ErrorLogger.Println(err)? If I use Go’s std log then I miss out on the error / info abstraction.

@montanaflynn

Nevermind the problem remains even without the logs, just took over a hundred requests before it happened.

https://gist.github.com/montanaflynn/bb002f8212e9cc7f75af5cc03e7a5fd8

...
HTTP/1.1 200     3.66 secs:    7742 bytes ==> GET  /img-without-logs
HTTP/1.1 500     3.68 secs:      36 bytes ==> GET  /img-without-logs
HTTP/1.1 200     0.84 secs:    7742 bytes ==> GET  /img-without-logs
...

@montanaflynn

I removed any third party packages and can reproduce with standard library:

This code returns the error / 500 response every so often.
This code does not return an error / 500 response afaik.

The difference in the code that doesn’t return an error is I removed all the nodego logger code including init nodego.OverrideLogger() and nodego.WithLoggerFunc middleware wrapper.

@iangudger

It seems that the problem could still be logging as you include nodego.OverrideLogger() in the problematic one, but not the non-problematic one.

@iangudger

By the way, you can use nodego.ErrorLogger with nodego.WithLoggerFunc. Maybe we need to clarify the documentation.

@marcelogrsp

Hi all, I am getting the same error.
It works when Testing but doesn’t work when I send HTTP POST request.
Actually it works via POST request after I send 3 or more requests.

@iangudger

Мне хочется вытащить волосы; это либо супер просто, и у меня есть замораживание мозга, или это не так просто.

Что я хочу

Я пытаюсь отключить сокращенный URL-адрес с помощью firebase, когда пользователь переходит к:
myapp.firebaseappurl.com/url/SHORTENEDLINK
SO не позволит мне добавить сокращенный URL

Я хотел бы, чтобы результат был:

{
  "url": "https://stackoverflow.com/info/45420989/sphinx-search-how-to-use-an-empty-before-match-and-after-match"
}

Что я пробовал

firebase.json файл:

{
  "hosting": {
    "public": "public",
    "rewrites": [ {
    "source": "/url/:item",
      "destination": "/url/:item"
    } ]
  }
}

index.js файл:

const functions = require('firebase-functions');

exports.url = functions.https.onRequest((requested, response) => {

    var uri = requested.url;
    request({
        uri: uri,
        followRedirect: true
      },
      function(err, httpResponse) {
        if (err) {
          return console.error(err);
        }
        response.send(httpResponse.headers.location || uri);
      }
    );

});

Результат

Когда я перехожу к myapp.firebaseappurl.com/url/SHORTENEDLINK, я получаю следующее:

Error: could not handle the request

4b9b3361

Ответ 1

Вы пытались использовать синтаксис { source: '/url/**' }?

Вы можете использовать что-то вроде этого:

{
  "hosting": {
    "public": "public",
    "rewrites": [ {
    "source": "/url/**",
    "function": "/url"
    }]
  }
}

а затем вы можете проанализировать URL-адрес из запроса.

 exports.url = functions.https.onRequest((req, res) => { 
   // parse the url from the req and redirect to the correct link
 });

Ответ 2

Вы видите Error: could not handle the request, поскольку, вероятно, было исключение и оно было отключено.

Проверьте свои журналы, используя:

firebase functions:log

Подробнее см. docs

Вот как я получил URL-адрес без искажений для работы

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const http = require('http');
const urlP = require('url');

const unshorten = (url, cb) => {
  const _r = http.request(
    Object.assign(
      {},
      urlP.parse(url),
      {
        method: 'HEAD',
      }
    ),
    function(response) {
      cb(null, response.headers.location || url);
    }
  );
  _r.on('error', cb);
  _r.end();
};

const resolveShortUrl = (uri, cb) => {
  unshorten(uri, (err, longUrl) => {
    if (longUrl === uri) {
      cb(null, longUrl);
    } else {
      resolveShortUrl(longUrl, cb);
    }
  });
};

exports.url = functions.https.onRequest((requested, response) => {
  var uri = requested.query.url;
  resolveShortUrl(uri, (err, url) => {
    if (err) {
      // handle err
    } else {
      response.send({ url });
    }
  });
});

Вы можете сразу же последовать примеру hello world и использовать приведенный выше код как ваш function.

В приведенном выше коде используются запросы HEAD, чтобы заглянуть в поле «Местоположение» заголовков и решает, может ли URL-адрес еще больше не сокращаться.

Это легче, так как запросы HEAD не требуют никакого тела (таким образом избегая разбора тела). Кроме того, никакой третьей стороне lib не требуется!

Также обратите внимание, что URL-адрес передан как параметр запроса. Таким образом, запрос будет

http://<your_firebase_server>/url?url=<short_url>

Сохраняет проблемы с повторной записью URL. Плюс семантически имеет смысл.

Ответ 3

Я думаю, что ваш код в порядке. То, что вы делаете неправильно, заключается в том, что вы используете обозначения Express-js в firebase.json rewrites node. (часть :item). Они не работают в базе данных Firebase Realtime.

Итак, вместо этого измените firebase.json на следующее: —

 {
  "hosting": {
    "public": "public",
    "rewrites":  {
    "source": "YOUR SHORTENED URL",
    "destination": "YOUR ORIGINAL URL"
  } 
  }
}

Это также защищенный подход в облачных функциях для Shortcut Shortbase URL sample.

Ответ 4

Сначала убедитесь, что вы правильно получили запрос с укороченным URL-адресом.

const functions = require('firebase-functions');

const express = require('express');
var express_app = express();
express_app.use(body_parser.text({type: ()=>true}));
express_app.all('*', (req, res) => {
    console.log(req.path);
    res.send(JSON.stringify(req.path));
});
exports.url = functions.https.onRequest(express_app);

Теперь, когда вы посещаете myapp.firebaseappurl.com/url/SHORTENEDLINK, вы должны увидеть SHORTENEDLINK в виде обычного текста. Когда это работает, попробуйте перенаправить.

const functions = require('firebase-functions');
const express = require('express');
const request = require('request');
var express_app = express();
express_app.use(body_parser.text({type: ()=>true}));
express_app.all('*', (req, res) => {
    var url = req.path;
    request({
        uri: uri,
        followRedirect: true
      },
      function(err, httpResponse) {
        if (err) {
          return console.error(err);
        }
        res.send(httpResponse.headers.location || uri);
      }
    );
});
exports.url = functions.https.onRequest(express_app);

Также хорошая практика npm install с --save, чтобы они оказались в packages.json. Хотя firebase копирует вашу папку node_modules, большинство других платформ SaaS запускаются npm install.

If the above solutions don’t work, one thing you can try is to enable all your apache modules to make sure that there isn’t some module you need that somehow got accidentally disabled.

For example, how I found the cause of my problem was to replace all instances of #LoadModule with LoadModule in all my Apache config files. Since that solved the problem for me, therefore I knew that my problem was not a missing «KeepAlive» directive argument, but rather, my problem was a missing dependency.

Because, remember, .so files are basically static libraries. Having a module enabled does not mean it will get used, but having one disabled does mean that it can’t get used, and therefore, anything that depends on it will necessarily fail.

Note: this answer has received some down-votes due to the fact that my initial answer seemed to suggest leaving all the modules enabled, forever. While you could theoretically do that without necessarily breaking anything, it’s obviously not a best practice solution.

So, please understand, I am merely suggesting this as a troubleshooting step, not a final solution.

Also, please note: I use a special git project to track all of my local machine’s apache config files. That way I can do these sorts of global search-and-replace operations in my apache config working directory, as a troubleshooting step. If enabling all modules succeeds, then try disabling them again one-by-one and restarting apache in between, until you find which module it is that needs to remain enabled. Once you’ve figured that out, then reset the repo back to its original state, and only enable that one module that needs to remain enabled.

You will also find that using git to track your apache config files cleans up those directories, since you won’t be needing those old-fashioned .bak and .default files anymore.

Понравилась статья? Поделить с друзьями:
  • Error could not get primary adapter handle
  • Error could not get file size of file как исправить
  • Error could not get file size of file skyrim
  • Error could not fork child process there are no available terminals 1
  • Error could not fork child process resource temporarily unavailable 1