“无服务器脱机:找不到路由。”在离线模式下运行AWS Lambda函数

时间:2019-08-30 21:52:47

标签: javascript routes serverless-framework serverless

这个问题与Serverless offline not getting route几乎相同,但是由于没有回答,我再次询问。我正在尝试按照https://medium.com/@awesome1888/how-to-use-serverless-locally-with-webpack-and-docker-5e268f71715这篇文章介绍如何使用Serverless部署Lambda函数。

我的目录结构如下:

> tree -I node_modules
.
├── package-lock.json
├── package.json
├── serverless.yml
├── src
│   ├── handler.js
│   └── index.js
└── webpack.config.js

serverless.yml读取的地方

service: my-first-lambda

plugins:
  - serverless-webpack
  - serverless-offline

provider:
  name: aws
  runtime: nodejs10.x
  region: us-east-1
  stage: dev

functions:
  hello:
    handler: src/handler.main
    events:
      - http:
        path: /hello
        method: any

custom:
  webpack:
    includeModules: true

src/index.js阅读

import moment from 'moment';

const handler = async (event, context) => {
  const body = await new Promise((resolve) => {
    setTimeout(() => {
      resolve(`Hello, this is your lambda speaking. Today is ${moment().format('dddd')}`)
    }, 2000);
  });
  return {
    statusCode: 200,
    body,
  };
}

export default handler;

src/handler.js阅读

export { default as main } from './index';

webpack.config.js

const path = require("path");
const nodeExternals = require("webpack-node-externals");
const slsw = require("serverless-webpack");

module.exports = {
  entry: slsw.lib.entries,
  target: "node",
  mode: slsw.lib.webpack.isLocal ? "development" : "production",
  externals: [nodeExternals()],
  output: {
    libraryTarget: "commonjs",
    path: path.join(__dirname, ".webpack"),
    filename: "[name].js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env"],
              plugins: ["@babel/plugin-proposal-object-rest-spread"]
            }
          }
        ]
      }
    ]
  }
};

问题是当我以离线模式启动该功能时,似乎只有一条非常具体的路线:

> 
npx serverless offline start --region us-east-1 --noTimeout --port 3000 --host 0.0.0.0
Serverless: Bundling with Webpack...
Time: 1203ms
Built at: 08/30/2019 2:35:10 PM
         Asset      Size       Chunks             Chunk Names
src/handler.js  6.81 KiB  src/handler  [emitted]  src/handler
Entrypoint src/handler = src/handler.js
[./src/handler.js] 42 bytes {src/handler} [built]
[./src/index.js] 1.64 KiB {src/handler} [built]
[moment] external "moment" 42 bytes {src/handler} [built]
Serverless: Watching for changes...
Serverless: Starting Offline: dev/us-east-1.

Serverless: Routes for hello:
Serverless: POST /{apiVersion}/functions/my-first-lambda-dev-hello/invocations

Serverless: Offline [HTTP] listening on http://0.0.0.0:3000
Serverless: Enter "rp" to replay the last request

如果我转到http://localhost:3000/hello,则会收到以下答复:

{"statusCode":404,"error":"Serverless-offline: route not found.","currentRoute":"get - /hello","existingRoutes":["post - /{apiVersion}/functions/my-first-lambda-dev-hello/invocations"]}

有人知道为什么这行不通吗? (我细读过https://serverless.com/framework/docs/,但无法快速找到答案)。

3 个答案:

答案 0 :(得分:5)

我遇到了这个问题,如果有人遇到,这个github comment fixed my issue

您可以运行$ sls offline start --noPrependStageInUrl或将以下内容添加到serverless.yml文件中

custom:
  serverless-offline:
    noPrependStageInUrl: true

根据评论:

我在6+上都遇到了这个问题,这是由于它现在默认将登台名称附加到url路径。要还原为旧方法,您需要在cli或无服务器文件定制中添加--noPrependStageInUrl:serverless-offline noPrependStageInUrl:true以还原为先前的设置。我正在对其进行测试,但@dherault的功能并未反映AWS中实际发生的情况。

我正在使用serverless-offline: "6.7.0",而我的index.handler如下:

const serverless = require("serverless-http");
const express = require("express");
const app = express();

app.get("/", function (req, res) {
  res.send("Hello World!");
});

module.exports.handler = serverless(app);

还有我的serverless.yml

plugins:
  - serverless-offline

custom:
  serverless-offline:
    noPrependStageInUrl: true

provider:
  name: aws
  runtime: nodejs12.x
  stage: dev
  region: eu-west-2

functions:
  app:
    handler: src/index.handler
    events:
      - http: ANY /
      - http: "ANY {proxy+}"

很抱歉,这并不是一个很好的答案,但希望有人遇到了这个问题,这是解决他们的问题的方法。

答案 1 :(得分:2)

好像您的serverless.yml文件中存在空格问题。

尝试在path块下缩进methodhttp

functions:
  hello:
    handler: src/handler.main
    events:
      - http:
          path: /hello
          method: any

答案 2 :(得分:0)

使用无服务器模板设置快速示例:

CurrentCulture

输出:

CurrentCulture

第1步:因此,使用api生成了一个新的nodejs示例:

sls create -h

第二步:安装脱机服务器:

create ........................ Create new Serverless service
--template / -t .................... Template for the service. Available templates: "aws-clojure-gradle", "aws-clojurescript-gradle", "aws-nodejs", "aws-nodejs-typescript", "aws-alexa-typescript", "aws-nodejs-ecma-script", "aws-python", "aws-python3", "aws-groovy-gradle", "aws-java-maven", "aws-java-gradle", "aws-kotlin-jvm-maven", "aws-kotlin-jvm-gradle", "aws-kotlin-nodejs-gradle", "aws-scala-sbt", "aws-csharp", "aws-fsharp", "aws-go", "aws-go-dep", "aws-go-mod", "aws-ruby", "aws-provided", "azure-nodejs", "cloudflare-workers", "cloudflare-workers-enterprise", "cloudflare-workers-rust", "fn-nodejs", "fn-go", "google-nodejs", "google-python", "google-go", "kubeless-python", "kubeless-nodejs", "openwhisk-java-maven", "openwhisk-nodejs", "openwhisk-php", "openwhisk-python", "openwhisk-ruby", "openwhisk-swift", "spotinst-nodejs", "spotinst-python", "spotinst-ruby", "spotinst-java8", "plugin" and "hello-world"

step3:在serverless.yml中

sls create -t aws-nodejs-ecma-script -n service-name-hello-world

第4步:启动本地服务器

npm install serverless-offline -D

github示例

plugins:
  - serverless-webpack
  - serverless-offline

serverless.yml

要在无服务器框架中定义api,您需要遵守yaml格式,而在path变量中,无需以'/ hello'开头,只需'hello'即可。

serverless offline start -r us-west-1 --stage dev