req.query返回NULL"/>
GET and req.query返回NULL
我的应用程序有几条运行良好的路由。但是,当通过客户端的输入请求使用GET,req.query和'findOne()'猫鼬方法来获取单个文档(dev)时,它在服务器上给了我“未定义/ NULL”的结果。有人知道如何使其工作吗?
CLIENTE侧:
const [name, setName] = useState('');
async function handleSubmit(e) {
e.preventDefault();
const response = await api.get('/devs', { name })
const { _id } = response.data;
console.log(_id)
localStorage.setItem('dev', _id);
history.push('/profile')
}
<form onSubmit={handleSubmit}>
<label htmlFor="busca">Busca Rápida de Usuários</label>
<input
id="busca"
type="busca"
placeholder="Digite o usuário para acessá-lo"
value={name}
onChange={e => setName(e.target.value)}
required
/>
<button className="btn" type="submit">Buscar</button>
</form>
api.js文件
import axios from 'axios';
import { getToken } from "./auth";
const api = axios.create({
baseURL: "http://localhost:5555",
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
});
api.interceptors.request.use(function (config) {
const token = getToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default api;
服务器端:
Controller.js
async getDev(req, res, next) {
try {
const { name } = req.query;
const dev = await Dev.findOne({ name });
console.log(dev)
if (!dev) {
return next(new Error('Dev does not exist'));
} res.send({
dev
})
} catch (error) {
next(error)
}
},
路线:
routes.get('/devs', DevController.allowIfLoggedin, DevController.grantAccess('readAny', 'profile'), DevController.getDev);
routes.get('/profile', DevController.allowIfLoggedin, DevController.grantAccess('readAny', 'profile'), DevController.showDev);
routes.delete('/devs/:_id', DevController.allowIfLoggedin, DevController.grantAccess('deleteAny', 'profile'),DevController.delete);
回答如下:您可以试试吗?>
await api.get(`/devs?name=${name}`);
更多推荐
GET and req.query返回NULL
发布评论