【问题标题】:How to pass parameter in url, with a colon in the javascript server side for NodeJS backend?如何在 url 中传递参数,在 NodeJS 后端的 javascript 服务器端使用冒号?
【发布时间】:2020-12-14 17:37:36
【问题描述】:

我正在尝试将数字 id 作为 URL 中的参数传递给服务器。我做错了什么?

我有一个任务管理器应用程序,可以在其中读取任务,用户可以通过其 id 读取任务,现在我通过输入 id (5e8b) 直接在邮递员中传递它:

{{url}}/tasks/5e8b

但我无法让它在浏览器中运行,这是我的 Html 代码:

<h1>Read Task by Task ID</h1>
    <form id="task-id-form">
        <input type="text" id="task-id"><br> <br>
        <button id="task-id-button">Find Task</button>
        <p id="task-id-display"></p>
    </form>

而我的服务器端 JS 代码是(不起作用):


const readTaskForm = document.querySelector( "#task-id-form" );
readTaskForm.addEventListener( "submit", ( e ) => {
    const readTaskId = document.querySelector( "#task-id" ).value;
    const params = { id: readTaskId }; // new addition
    const urlParams = new URLSearchParams( Object.entries( readTaskId ) );

    fetch( "http://localhost:3000/tasks/" + urlParams, {
        method: 'get',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json',
            "Authorization": `Bearer` + `${ inMemoryToken }`
        }
    } ).then( res => res.json() )
        .then( res => {
            console.log( res );
           
        }
        );
} );

我的后端节点 js 代码如下(在 postman 中正常工作):

router.get( "/tasks/:id", auth, async ( req, res ) => {
    const _id = req.params.id;
    try {
        const task = await Task.findOne( { _id, owner: req.user._id } );
        if ( !task ) {
            return res.status( 401 ).send( { error: "Task id not found" } );
        }
        res.send( { task } );
    } catch ( e ) {
        res.status( 400 ).send( e );
    }
} );

非常感谢任何帮助。

【问题讨论】:

  • 如果你的 URL 是这样形成的:'{{url}}/tasks/id=5e8b' 会发生什么?
  • 对不起,浏览器中的url为:localhost:3000/tasks/5e8b
  • 我认为它不适用于 id=5e8b
  • 抱歉,是的,我需要重新阅读您的问题
  • 请定义“不工作”和“让它工作”。您在浏览器工具或服务器控制台中显示了哪些特定行为以及您看到哪些错误消息?

标签: javascript html node.js forms url-parameters


【解决方案1】:

我认为你不必使用 URLSearchParams 作为参数,只需使用 readTaskId

        const readTaskForm = document.querySelector("#task-id-form");
        readTaskForm.addEventListener("submit", (e) => {
          const readTaskId = document.querySelector("#task-id").value;
          //const params = { id: readTaskId }; // new addition

          //const urlParams = new URLSearchParams(Object.entries(readTaskId));
          fetch("http://localhost:3000/tasks/" + readTaskId, {
            method: "get",
            headers: {
              Accept: "application/json, text/plain, */*",
              "Content-Type": "application/json",
              Authorization: `Bearer` + `${inMemoryToken}`
            }
          })
            .then((res) => res.json())
            .then((res) => {
              console.log(res);
            });
        });

【讨论】:

  • 抛出错误 - 400 Bad request at line ` fetch( "localhost:3000/tasks" + readTaskId, { `
  • 您是否在“任务”末尾设置斜线? ` fetch( "localhost:3000/tasks/" + readTaskId, { ` . 向我们显示最终 url 的警报或 console.log (也带有参数)
  • 是的,我在 URL 的末尾加上了斜杠 fetch( "http://localhost:3000/tasks/" + readTaskId, {,我在后端的路由是:router.get( "/tasks/:id", auth, async ( req, res ) =&gt; { 另外,你的 Blahbox 网站设计得很好 :)
  • 感谢 Blahbox!。您应该向我们发送有关该错误的更多信息。完整的控制台错误,一些屏幕截图......也许你的标题有问题。
  • 嗨,Matias,这是控制台的屏幕截图:ibb.co/gVdrczb
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-22
  • 2023-03-24
  • 2014-11-24
  • 1970-01-01
  • 2019-06-02
  • 1970-01-01
  • 2021-11-15
相关资源
最近更新 更多