简体   繁体   English

获取 REST API 的请求响应错误

[英]Bad request response to fetch REST API

I have built an API and app that uses that API.我已经构建了一个 API 和使用该 API 的应用程序。 When I POST method via Postman, it works fine, but when I try fetching it via app, I get a bad request 400 status response.当我通过 Postman POST方法时,它工作正常,但是当我尝试通过应用程序获取它时,我收到一个错误的请求 400 状态响应。 What am I doing wrong?我究竟做错了什么?

Here is my JavaScript code:这是我的 JavaScript 代码:

const myForm = document.getElementById('loginForm');

myForm.addEventListener('submit', function(e) {
  e.preventDefault();

  const url = 'https://thawing-peak-69345.herokuapp.com/api/auth';

  const myHeaders = new Headers();
  myHeaders.append('Accept', 'application/json, text/html, */* ');
  myHeaders.append('Content-Type', 'application/json, charset=utf-8')


  const formData = {
    email: this.email.value,
    password: this.password.value
  };


  console.log(formData);

  const fetchOptions = {
    method: 'POST',
    mode: 'no-cors',
    cache: 'no-cache',
    headers: myHeaders,
    body: JSON.stringify(formData)
  };

  fetch(url, fetchOptions)
    .then(res => res.json())
    .then(res => console.log(res))
    .catch(err => console.log(err))

})

Request要求索取照片

Response回复在此处输入图片说明

Headers request :标头请求在此处输入图片说明

Headers response :标题响应在此处输入图片说明

You said:你说:

 mode: 'no-cors',

This is a declaration that you are not doing anything that requires permission be granted with CORS.这是声明您没有做任何需要获得 CORS 许可的事情。 If you try to do anything that does need permission, it will be silently ignored.如果您尝试做任何需要许可的事情,它将被默默忽略。

 myHeaders.append( 'Content-Type', 'application/json, charset=utf-8')

Setting the Content-Type header to a value not supported by the HTML form element's type attribute requires permission from CORS.Content-Type标头设置为 HTML form元素的type属性不支持的值需要来自 CORS 的许可。 application/json is not such a value. application/json不是这样的值。

Consequently, the request is sent as text/plain .因此,请求作为text/plain发送。

Since it isn't marked as being JSON, the server throws a 400 error.因为它没有被标记为 JSON,所以服务器会抛出 400 错误。

You need to:你需要:

  • Remove mode: 'no-cors',删除mode: 'no-cors',
  • Make sure that the service you are making the request to will use CORS to grant you permission (or to use a service on the same origin as the request).确保您向其发出请求的服务将使用 CORS 授予您权限(或使用与请求同源的服务)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM