【问题标题】:500 error on .net core web api post using fetch.net core web api post使用fetch出现500错误
【发布时间】:2019-10-31 18:20:20
【问题描述】:

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

控制器返回 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

【问题讨论】:

  • 添加try catch并返回异常来查看问题或只是调试,是_customersService.AddAsync的问题
  • 控制器中没有异常。我可以看到它击中返回 OK(客户)。 fetch 确实有问题。
  • 您能否在网络选项卡/提琴手中检查 API 响应状态代码是什么?是否有任何管道从 Web API 抛出 500 错误?
  • 将该信息添加到问题中
  • 尝试删除 'Accept': 'text json', 并尝试使用 Postman

标签: javascript c# .net-core asp.net-core-webapi fetch-api


【解决方案1】:

我也有同样的问题。显示错误,因为我没有在标头发送“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);
  });
  
`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 2021-09-14
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多