Node.js + static content served by Google App Engi

2019-07-11 23:31发布

问题:

The Google Cloud documentation isn't very precise on the available syntax for the app.yaml file used for my Node.js application.

I used the syntax described in the Python documentation for GAE, from which I've found the handlers mecanism:

    handlers:
    - url: /index.html
      static_files: /public/index.html
      upload: /public/index.html

I've avoid my expressjs rule to serve the /public/index.html content and finally I got a 404 error, meaning GAE is not serving my page as a static content:

    $ curl -i "http://my-project/index.html"
    HTTP/1.1 404 Not Found
    ...

Do you have any clue on this? Node.js is relevant for making APIs, generating dynamic content... But I prefer using the Google backends or even a Nginx server to handle static contents.

Update

Removing the leading slashes didn't fixed the issue. I slightly changed my app.yaml configuration:

    handlers:
    - url: /api/.*
      secure: always
      script: app.js
    - url: /.*
      secure: always
      static_dir: public

And I still get 404 Not found on /index.html, and getting the correct 200 OK answser when calling /api/stuff.

Here is my project tree structure:

    Project root
    |- app.js
    |- app.yaml
    |- package.json
    |- public/
    |  `-- css/
    |     `-- style.css
    |  `-- js/
    |     `-- main.js
    |  `-- index.html

回答1:

The examples at the very documentation page should normally suffice.

You have a leading / in the static_files and upload values, which should be just relative paths to the top of your app dir.

There could be other reasons as well, the starting point would be the logs for your app, either on your development server or on GAE if already deployed.

Update:

According to the Static directory handlers doc:

A static directory example:

handlers:
# All URLs beginning with /stylesheets are treated as paths to static files in
# the stylesheets/ directory.
- url: /stylesheets
  static_dir: stylesheets

url

A URL prefix. This value uses regular expression syntax (and so regexp special characters must be escaped), but it should not contain groupings. All URLs that begin with this prefix are handled by this handler, using the portion of the URL after the prefix as part of the file path.

Based on this quote I'd suspect the wildcards in the url of the app.yaml's handler spec may be causing issues (for example the /index.html might actually be expanded to /index.html/ by the static_dir parsing logic), I'd replace the url to clearly indicate a directory, like this:

- url: /
  secure: always
  static_dir: public

I'm not a fan of tying the top level / of the app's namespace to a static dir, but it may be OK for a generally static app. Make sure you always keep this handler spec last in your app.yaml file to avoid issues.