Javascript 获取请求查询参数不是';t申请
我试图在Express中的get请求中使用查询参数,但请求正文中没有参数 在前端Javascript 获取请求查询参数不是';t申请,javascript,node.js,reactjs,express,Javascript,Node.js,Reactjs,Express,我试图在Express中的get请求中使用查询参数,但请求正文中没有参数 在前端 query () { if (window.location.href === 'http://localhost:3000/profile') { window.location.href = `?contributer=${localStorage.getItem('username')}`; } fetch('http://localhost:3002/get-user
query () {
if (window.location.href === 'http://localhost:3000/profile') {
window.location.href = `?contributer=${localStorage.getItem('username')}`;
}
fetch('http://localhost:3002/get-user-recipes')
.then(response => response.json())
.then(data => {
this.setState({
apiResponse: data
});
});
}
在后端
app.get('/get-user-recipes', (req, res, next) => {
console.log(req.query); // returns {}
});
app.get('/get-user-recipes', (req, res, next) => {
console.log(req.query); // would return { one: '1', two: ,'2' }
});
好吧,我知道了。参数需要在express路径中,因此正确的代码是
获取(
http://localhost:3002/get-用户配方?contributer=${localStorage.getItem('username')}
)好的,我猜出来了。参数需要在express路径中,因此正确的代码是
获取(
http://localhost:3002/get-用户配方?contributer=${localStorage.getItem('username')}
)查询参数通常位于url的末尾,并使用?
例如:
//在前端
发出get请求以说明:
http://localhost:3002/get-user-recipes?one=1&two=2
此处的查询参数是一个值为“1”的参数和两个值为“2”的参数
//在后端
app.get('/get-user-recipes', (req, res, next) => {
console.log(req.query); // returns {}
});
app.get('/get-user-recipes', (req, res, next) => {
console.log(req.query); // would return { one: '1', two: ,'2' }
});
查询参数通常位于url的末尾,并使用
?
例如:
//在前端
发出get请求以说明:
http://localhost:3002/get-user-recipes?one=1&two=2
此处的查询参数是一个值为“1”的参数和两个值为“2”的参数
//在后端
app.get('/get-user-recipes', (req, res, next) => {
console.log(req.query); // returns {}
});
app.get('/get-user-recipes', (req, res, next) => {
console.log(req.query); // would return { one: '1', two: ,'2' }
});
首先,您的localStorage.getItem参数无效,然后您没有向后端发送任何数据,因此您的req.query是一个空对象。@这不是意味着req.query={contributer:undefined}是的,您是对的。但这并没有发生,这意味着fetch没有发送查询对象。我不知道为什么,通过查看您的代码,除了contributer.comment out if语句之外,其他一切似乎都很好,并检查req.query returns是否仍然返回相同的{}。首先,您的localStorage.getItem参数无效,那么您没有向后端发送任何数据,因此您的req.query是一个空对象。@这不是意味着req.query={contributer:undefined}是的,您是对的。但这并没有发生,这意味着fetch没有发送查询对象。我不知道为什么,通过查看您的代码,除了contributer.comment of the if语句之外,其他一切似乎都很好,并检查req.query返回的是否仍然返回相同的{}很好,您可以找到它很好,您可以找到它