我正在使用一个应用程序(
nodeJS
),它需要在请求正文中捕获电子邮件和密码才能删除令牌。
我在前端使用 React 来使用 fetch
来发布帖子,但是,当我使用 onClick
事件发布帖子时,我观察 API 的控制台,正文未正确形成。
{ '{"email":"[电子邮件受保护]","password":"Johnismyname"}': ' ' }
问题不在于 API,因为我用邮递员测试了它并且工作正常。 我猜问题出在反应代码中,因为我仍在学习。 这是react中的代码:
import { Link } from "react-router-dom"
import { useRef, useState } from 'react';
export default function Login() {
const [token, setToken] = useState('')
const LOGIN_API_URL = "http://localhost:3010/api/v1/users/login"
const GET_USER_API_URL = "http://localhost:3010/api/v1/users/getuser"
const userEmail = useRef();
const userPassword = useRef();
async function apiCall(email, password, tokenUrl, userUrl) {
const body = JSON.stringify({
email: email,
password: password
});
const fetchConfig = {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
body
}
const response = await fetch(tokenUrl, fetchConfig)
const data = await response.json()
console.log(data);
return setToken(data.token)
}
return (
<div className="login-container">
<div className="inputs-container">
<h1>Login</h1>
<input ref={userEmail} type="email" name="email" id="email" placeholder="email"/>
<input ref={userPassword }type="password" name="password" id="password" placeholder="password" />
<div
className="button-submit"
onClick={() => {
apiCall(userEmail.current.value, userPassword.current.value, LOGIN_API_URL, GET_USER_API_URL)
}}
>
Join
</div>
</div>
<h3><Link className="register hover-expands" to="/register">Register</Link></h3>
</div>
)
}
这是由于您在标头中提供的 Content-Type 不正确造成的。将
application/x-www-form-urlencoded
替换为 application/json
以获得所需的结果。
const fetchConfig = {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
body,
};
将这行代码
"Content-Type": "application/x-www-form-urlencoded"
更改为"Content-Type": "application/json"