如何在url中传递参数,并在JavaScript服务器端的NodeJS后端使用冒号? [英] How to pass parameter in url, with a colon in the javascript server side for NodeJS backend?
问题描述
我正在尝试将数字ID作为参数传递给服务器.我在做什么错了?
I am trying to pass a numeric id as a parameter in the URL to the server. What am I doing wrong?
我有一个任务管理器应用程序,可以在其中读取任务,用户可以通过其ID读取任务,现在我通过输入ID(5e8b)作为邮递员直接将其传递为:
I have a task manager app in which to read a task, users can read a task by its id, now I am passing this directly in postman by entering id (5e8b) as:
{{url}}/tasks/5e8b
但是我无法使其在浏览器中工作,这是我的HTML代码:
But I couldn't make it work in the browser, here is my Html code :
<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代码是(不起作用):
And my server-side JS code is (which is not working) :
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中正常工作):
And my backend node js code is as (which is working correctly in 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 );
}
} );
我们非常感谢您的帮助.
Any help is highly appreciated.
推荐答案
我认为您不必使用 URLSearchParams 作为参数,只需使用 readTaskId >
I think you don't have to use URLSearchParams as a parameter, simply use 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);
});
});
这篇关于如何在url中传递参数,并在JavaScript服务器端的NodeJS后端使用冒号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!