Node.js 如何使用express从客户端到服务器获取get/参数?
我正在尝试使用react plus NODE.js server和express创建一个web,但我无法在客户端(localhost:3000)上获取get函数的参数,当我尝试在服务器api(localhost:5000)上进行此操作时,它可以工作,而在客户端的另一端,我无法从浏览器url获取url/参数 服务器代码:Node.js 如何使用express从客户端到服务器获取get/参数?,node.js,reactjs,express,parameters,Node.js,Reactjs,Express,Parameters,我正在尝试使用react plus NODE.js server和express创建一个web,但我无法在客户端(localhost:3000)上获取get函数的参数,当我尝试在服务器api(localhost:5000)上进行此操作时,它可以工作,而在客户端的另一端,我无法从浏览器url获取url/参数 服务器代码: const express = require('express'); const bodyParser = require('body-parser'); c
const express = require('express');
const bodyParser = require('body-parser');
const pgp = require('pg-promise')(/* options */)
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.get('/aboutus',urlencodedParser, (req, result) => {
console.log(req.query);
result.send( req.query.id);
});
app.get('/1',urlencodedParser, (req, res) => {
console.log(req.url)
res.send( req.url);
})
客户:
import React, { Component } from 'react';
class AboutUs extends Component {
state = {
about: '',
about1: '',
};
componentDidMount() {
fetch('/aboutus')
.then(res => res.json())
.then(
(result) => {
this.setState({
about: result,
});
},
(error) => {
this.setState({
about: error
});
}
)
fetch('/1')
.then(res => res.json())
.then(
(result) => {
this.setState({
about1: result,
});
},
)
}
render() {
return (
<div>
<p>{'abc' + JSON.stringify(this.state.about)}</p>
<p>{'def ' + JSON.stringify(this.state.about1)}</p>
</div>
);
}
}
export default AboutUs;
import React,{Component}来自'React';
类AboutUs扩展组件{
状态={
关于:'',
大约1:“”,
};
componentDidMount(){
获取('/aboutus')
.then(res=>res.json())
.那么(
(结果)=>{
这是我的国家({
关于:结果,
});
},
(错误)=>{
这是我的国家({
关于:错误
});
}
)
获取('/1')
.then(res=>res.json())
.那么(
(结果)=>{
这是我的国家({
大约1:结果,
});
},
)
}
render(){
返回(
{'abc'+JSON.stringify(this.state.about)}
{'def'+JSON.stringify(this.state.about1)}
);
}
}
导出默认值;
我不确定我做错了什么,当我访问像localhost:5000/aboutus?id=abcd
这样的url时,res.send
输出“abcd”,但当我访问loclhost:3000/aboutus?id=efgs
时,我没有得到任何参数。也许我得换一种方法,但我找不到任何方法。
api的工作,例如,当我发送req.url时,我可以显示它,但我无法获取参数:
您以前在react项目上设置过代理吗?如果没有,那么在获取数据时应该指定服务器api的完整路径 取('http://localhost:5000/aboutus)而不是仅仅/大约 另外,请确保没有任何cors错误,这可能是在使用fetch调用请求时拒绝请求。代理在json中设置:“Proxy”:“localhost:5000”,get方法可以正确地将数据发送到react客户端,我进行了一些数据库查询并显示了它们,fetch中的整个url不起作用,即使当我发送req.url时,我也可以在react中显示它,但我只得到我在fetch中使用的url,当我添加任何参数时,它会忽略它,或者我不知道它会做什么。