無服務器V1目前無法使用狀態碼。但對於使用狀態碼無服務器插件
1.安裝插件
npm i serverless-plugin-multiple-responses --save
2.加入serverless.yml文件插件名稱
plugins:
- serverless-plugin-multiple-responses
3.在無服務器添加這個自定義代碼.yml文件(您可以根據您的要求更改此代碼)
custom:
defaultRegion: us-east-1
region: ${opt:region, self:custom.defaultRegion}
stage: ${opt:stage, env:USER}
standardRequest:
template:
application/json: ${file(./templates.yml):request}
standardResponseHeaders:
'Access-Control-Allow-Origin': "'*'"
'Content-Type': 'integration.response.body.headers.Content-Type'
'Expires': 'integration.response.body.headers.Expires'
'Cache-Control': 'integration.response.body.headers.Cache-Control'
'Pragma': "'no-cache'"
standardResponseTemplate: "$input.path('$.body')"
errorResponseHeaders:
'Access-Control-Allow-Origin': "'*'"
'Expires': "'Thu, 19 Nov 1981 08:52:00 GMT'"
'Cache-Control': "'no-cache, max-age=0, must-revalidate'"
'Pragma': "'no-cache'"
errorResponseTemplate: "$input.path('$.errorMessage')"
# Here we are defining what would be under "responses" in your HTTP event
# if you were not using the custom variables.
standardResponses:
200:
headers: ${self:custom.standardResponseHeaders}
templates:
'application/json;charset=UTF-8': ${self:custom.standardResponseTemplate}
404:
headers: ${self:custom.errorResponseHeaders}
templates:
'application/json;charset=UTF-8': ${self:custom.errorResponseTemplate}
properties:
SelectionPattern: '.*\"status\":404.*'
500:
headers: ${self:custom.errorResponseHeaders}
templates:
'application/json;charset=UTF-8': ${self:custom.errorResponseTemplate}
properties:
SelectionPattern: '.*\"status\":500.*'
redirectResponses:
# Since we want to return 302 upon a successful completion, we remove the
# built-in default of 200
200: false
302:
headers:
Location: "integration.response.body.headers.Location"
templates:
'application/json;charset=UTF-8': "$input.path('$.body')"
'text/html;charset=UTF-8': "$input.path('$.body')"
404:
headers: ${self:custom.errorResponseHeaders}
templates:
'application/json;charset=UTF-8': "$input.path('$.body')"
'text/html;charset=UTF-8': "$input.path('$.body')"
properties:
SelectionPattern: '.*\"status\":404.*'
500:
headers: ${self:custom.errorResponseHeaders}
templates:
'application/json;charset=UTF-8': "$input.path('$.body')"
'text/html;charset=UTF-8': "$input.path('$.body')"
properties:
SelectionPattern: '.*\"status\":500.*'
添加重定向URL在處理程序文件
module.exports.home =函數(事件上下文){ context.succeed({ 「位置」: 「https://test.com」})}
定義功能及其在serverless.yml文件的響應
迴應:$ {自我:custom.redirectResponses}