簡體   English   中英

簡單的 POST 請求在 Postman 中有效,但在瀏覽器中無效

[英]Simple POST request works in Postman but not in browser

我遇到了一個問題,即POST端點在 Postman 中運行時返回響應,但在瀏覽器中運行時卻沒有。

我已經通過無服務器在 AWS 上設置了一個 API 端點。 這是 .yml 的配置:

service: tableau-export-rest

provider:
  name: aws
  runtime: nodejs10.x
  region: eu-west-1
  stage: ${opt:stage, 'dev'}
  timeout: 900
  memorySize: 3008

functions:
  storeExportFiters:
    handler: index.storeExportFiters  
    events:
      - http: 
          path: /store-export-filters
          method: post
          cors: true 

端點解析器storeExportFiters (它是一個 lambda)現在只返回一條成功消息:

module.exports = (event, ctx, cb) => {
  return cb(null, {
    statusCode: 200,
    body: JSON.stringify({
      worked: true
    })
  });
}

當我將它部署到 AWS 並嘗試通過沒有正文或任何內容的POST請求從 Postman 訪問端點時,它會向我發送響應。 當我嘗試在瀏覽器中執行此操作時,我收到cors錯誤:

Access to XMLHttpRequest at ' https://myapi.com/store-export-filters ' from origin ' http://localhost:9003 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present在請求的資源上。

這是用於嘗試從端點獲取響應的瀏覽器代碼。 我將Axios用於 http 請求:

  axios.post('https://myapi.com/store-export-filters')
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });

我不明白為什么我會在這里收到 CORS 錯誤,尤其是因為它在我的機器上的 Postman 中有效。

您的 API 未針對跨源請求進行配置。 您需要配置您的服務器以允許這些請求。

Access-Control-Allow-Origin: *

這將允許您的 API 接收來自任何來源的請求, 但這可能是一個主要的安全問題。

將 API 配置為僅接受來自特定來源的請求可修復此問題。

Access-Control-Allow-Origin: hostname:port

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM