[英]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:你需要:
mode: 'no-cors',
删除mode: 'no-cors',
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.