簡體   English   中英

提取API Post方法不起作用

[英]Fetch API Post method is not working

fetch('http://localhost:9000/api/app/contact', {
    method: 'POST',
    headers: {
        'content-type': 'application/json'
    },
    body: JSON.stringify({
        email: this.state.email,
        contactNumber: this.state.phone,
        enquiry: this.state.msg
    })
})
.then(function(res) { return res.json() })
.then(function(data) {
    alert('We will contact you shortly') 
});

當我進行上述編碼時,遇到以下錯誤:

無法加載http:// localhost:9000 / api / app / contact :對預檢請求的響應未通過訪問控制檢查:所請求的資源上沒有'Access-Control-Allow-Origin'標頭。 因此,不允許訪問源' http:// localhost:8080 '。 如果不透明的響應滿足您的需求,請將請求的模式設置為“ no-cors”,以在禁用CORS的情況下獲取資源。

但是,當我嘗試郵遞員時,它可以成功工作。 請幫助我,我的提取api中是否缺少任何代碼。

以下是郵遞員POST請求和代碼。

在此處輸入圖片說明

以下代碼是Postman Post請求。

var data = JSON.stringify({
  "email": "test@gmail.com",
  "contactNumber": "0123456789",
  "enquiry": "Testing"
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:9000/api/app/contact");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "d5e08b69-5f0f-8193-e021-e2c3b1bfe1a3");

xhr.send(data);

在NodeJS服務器端,我已經在后端CORS了。

var express = require('express'),
    controller = require('./app.controller'),
    router = express.Router(),
    cors = require('cors');

var issue2options = {
  origin: true,
  methods: ['POST'],
  credentials: true,
  maxAge: 3600
};

router.post('/contact', cors(issue2options), controller.sendContactForm);
module.exports = router;

您需要為瀏覽器自行發送的CORS預檢添加顯式的OPTIONS處理:

app.options('/contact', cors(issue2options)); // enable preflight OPTIONS
router.post('/contact', cors(issue2options), controller.sendContactForm);

參見https://www.npmjs.com/package/cors#enabling-cors-pre-flight

郵遞員與瀏覽器不同。

要解決此問題,您需要http://localhost:9000/api/app/contact的服務器在其標頭中返回CORS標頭,例如Access-Control-Allow-Origin: *這樣的示例Access-Control-Allow-Origin: *

在此處閱讀以獲取詳細的CORS參考https://enable-cors.org/server.html

暫無
暫無

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

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