簡體   English   中英

在 ReactJS 中使用 Fetch 調用 POST API 時出現錯誤 415

[英]Error 415 when call POST API using Fetch in ReactJS

我想從 React 中的方法調用一個 API 進行注冊。 下面是我的 javascript 代碼:

     fetch('http://localhost:5001/api/Account', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            email: "hugh.daniel@gmail.com",
            name: "Hugh Daniel",
            password: "1234"
        })
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

這是我的控制器

    [HttpPost]
    public ResponseModel RegisterByEmail([FromBody]UserModel user)
    {
        return _accountService.RegisterEmail(user);
    }

但我總是收到這些錯誤在此處輸入圖片說明

我試圖在我的 javascript 代碼中添加mode: 'no-cors' ,但它使Content-Type設置為普通。 如果我像這樣使用 Postman 對其進行測試,則該 API 可以正常工作在此處輸入圖片說明

在此處輸入圖片說明

您首先需要與CORS作戰。 您不能針對不同於開發服務器所服務的domain:port API請求。 您在項目中使用Webpack嗎? 如果是,最簡單的方法是通過Webpack配置來設置API代理。 參見文檔 像這樣:

// webpack.config.js
devServer: {
    port: 3030,
    proxy: {
      '/api': {
        target: `http://localhost:5001`,
        secure: false
      }
    }
  }

現在,您必須從fetch地址參數中刪除host:port ,並且還要在請求設置中添加Accept標頭:

fetch('/api/Account', {
    method: 'post',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    // ...
  }
)

不要在主體中使用JSON.stringify發送請求,以下代碼將完成工作。

fetch('http://localhost:5001/api/Account', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: {
        email: "hugh.daniel@gmail.com",
        name: "Hugh Daniel",
        password: "1234"
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

嘗試這個

[ApiController]
[Consumes("application/json")]
[Produces("application/json")]
[Route("[controller]")]        
public class TestController : ControllerBase
{}

在js中:

await fetch(this.url, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });

來源: https : //pretagteam.com/question/angular-http-post-formdata-unsupported-media-type-from-c-controller

暫無
暫無

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

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