我尝试通过电子邮件检索特定用户,但收到此错误
CORS策略已阻止从源"http://localhost:3000"访问位于"http://localhost:8080/calore_counter/email.undefined"的XMLHttpRequest:请求的资源上不存在"Access-Control-Allow-Origin"标头。
我认为这与useParams未被axios请求识别有关,我在这方面做错了。
这是此页面的代码
import axios from 'axios';
import React, { useState, useEffect } from 'react'
import {useParams} from 'react-router-dom'
export default function ViewUser() {
const [user, setUser] = useState({
name:"",
email: "",
dob: "",
age: "",
suggestedCalories: "",
goal:"",
lifestyle:"",
weight:""
});
const { email } = useParams();
const onInputChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value });
};
useEffect(()=>{
}, [])
const onSubmit = async (e)=>{
e.preventDefault();
axios.get(`http://localhost:8080/calorie_counter/email.${email}`)
.then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
return (
<div className='col-md-6 offset-md-3 border rounded p-4 mt-2 shadow'>
<form onSubmit={(e) => onSubmit(e)}>
<div className='mb-3'>
<label htmlFor='Email' className='form-label'>
E-mail
</label>
<input
type={'text'}
className='form-control'
placeholder='Enter E-mail'
onChange= {(e) => onInputChange(e)}
value={email}
/>
<button type="submit" className='btn btn-outline-success'>Submit</button>
</div>
</form>
<div className='card'>
<div className='card-header'>
Details of user id :
<ul className='list-group list-group-flush'>
<li className='list-group-item'>
<b>Name: </b>
{user.name}
</li>
<li className='list-group-item'>
<b>Email: </b>
{user.email}
</li>
<li className='list-group-item'>
<b>Date of Brith: </b>
{user.dob}
</li>
<li className='list-group-item'>
<b>Age: </b>
{user.age}
</li>
<li className='list-group-item'>
<b>Suggested Calories: </b>
{user.suggestedCalories}
</li>
<li className='list-group-item'>
<b>Goal: </b>
{user.goal}
</li>
<li className='list-group-item'>
<b>LifeStyle: </b>
{user.lifestyle}
</li>
</ul>
</div>
</div>
</div>
)
}
我希望在数据库中输入现有用户的电子邮件,单击提交并通过其电子邮件接收使用。我知道后端工作,所以只有前端有问题。我尝试过在输入字段周围捣乱,但没有工作。这要么是输入字段或提交按钮有问题
1条答案
按热度按时间kd3sttzy1#
要解决
email
是undefined
的问题,您需要正确使用onInputChange函数,如下例所示。如果您仍然收到CORS问题,请在评论中告诉我。