GET and req.query返回NULL

编程入门 行业动态 更新时间:2024-10-07 19:18:21

GET and <a href=https://www.elefans.com/category/jswz/34/1771098.html style=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

本文发布于:2024-05-07 05:58:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:req   query   NULL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!