首页 > 解决方案 > .net core web api post使用fetch出现500错误

问题描述

我正在使用 带有.net core 3 web api的javascript fetch api https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch 。

控制器返回 OK(object) 但 fetch 收到 500 状态码。

这是控制器。我可以单步执行代码并查看它是否返回 Ok(customer)

[HttpPost]
        public async Task<IActionResult> PostCustomerAsync([FromBody] Customers customer)
        {

            await _customersService.AddAsync(customer);
            return Ok(customer);
        }
    }

这是获取。

   fetch("./api/customers",
        {
            method: "POST", body: JSON.stringify(data),
            headers: {
                'Accept': 'text json',
                'Content-Type': 'application/json'
            },
        })
         .then(function(response, error){
             console.log(error);
             console.log(response);
             if(!response.ok){
                 console.log(response);
                 throw Error(response.statusText);
             }
             return response;
         }).then(function(response){
             Toastr.success(`${data.firstname} ${data.lastname} has been successfully registered`);  
             const bookChapterTable = new BookChapterTable();     
         }).catch(function(error){
             console.log(error);
             Toastr.error(`An error occured : ${error}`);        
         })
  }

提取停止在 !response.ok

这是回应。

body: ReadableStream
locked: false
__proto__: ReadableStream
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 500
statusText: ""
type: "basic"
url: "https://localhost:44300/api/customers"

从网络选项卡

Request URL: https://localhost:44300/api/customers
Request Method: POST
Status Code: 500 
Remote Address: [::1]:44300
Referrer Policy: no-referrer-when-downgrade
date: Thu, 31 Oct 2019 18:34:14 GMT
server: Microsoft-IIS/10.0
status: 500
x-powered-by: ASP.NET
:authority: localhost:44300
:method: POST
:path: /api/customers
:scheme: https
accept: text json
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
content-length: 171

标签: javascriptc#.net-coreasp.net-core-webapifetch-api

解决方案


我有同样的问题。显示错误,因为我没有在标头发送“X-XSRF-Token”(它可以是“X-CSRF-TOKEN”,取决于系统)。如果有人有同样的问题,请确保您在标题处传递它。

fetch(signUpEmailUrl, {
      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
          'X-XSRF-Token': gettoken()
      },
      credentials: 'include',
      body: JSON.stringify({
          email: $('#sign_up_email').val(),
          firstName: $('#first_name').val(),
          lastName: $('#last_name').val(),
          token: $('#sign_up_token').val()
      })
  })
  .then(res => (res.json()))
  .then(data => {
      console.log(data);
      loginSuccess(data);
  })
  .catch(err => {
      console.log(err);
  });
  
`


推荐阅读