[英]Postman request works but my React request doesn't. Where is my mistake
我正在制作一個基本的完整堆棧來做應用程序。 我用 Java Spring 做后端。 當我使用 Postman 測試我的后端時,它運行良好,但是當我使用 React fetch 發送相同的請求時,它不起作用! 我想我的提取是錯誤的,但我無法理解。
function register(){
fetch('http://localhost:8080/auth/register',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(
{
'userName' : 'Pala',
'password' : 'sibop',
}
)
}
).then(
res => {
console.log("Result: " + res)
}
).catch(
err => {
console.log("Erorororor: " + err)
}
)}
function Home() {
return (
<div>
<h1>To Do!</h1>
<form>
<div id="signupArea">
<h2>Name</h2>
<input id="userName"/>
<h2>Password</h2>
<input id="password" type="password"/>
<button onClick={register}>SIGN UP</button>
<button>LOGIN</button>
</div>
</form>
</div>
)}export default Home
我的問題是什么?
您必須配置代理,出現 CORS 錯誤。
如果您使用的是 create-react-app。
https://create-react-app.dev/docs/proxying-api-requests-in-development/
我將"proxy": "http://localhost:8080"
到 package.json 並將獲取 url 更改為"/auth/register"
,現在它可以工作了,謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.