你好,我是一个新的表达,nodejs和react使用,我想做网络应用程序。现在我正在尝试使用一些GET参数来进行一些查询,我不知道应该怎么做,因为我无法获取它们。不确定我是需要使用一些新技术还是我只是做错了什么。
我的服务器:
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({text:req.url});
});
我的客户端:
componentDidMount() {
fetch('/aboutus')
.then(res => res.json())
.then(
(result) => {
this.setState({
about: result,
});
},
(error) => {
this.setState({
about: error
});
}
)
和我的依赖项:
{
"name": "example-react-app-express",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"proxy": "http://localhost:5000/",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
api工作正常,发送数据,但是使用req变量会给我fetch中使用的url(当我fetched/aboutus?id=5时,我确实获得了id参数,但是似乎不应该总是从浏览器获取url并获取该url.。。)我看到一些人在使用CORS,但我不知道是否需要它,或者什么是最好的方法
HTTP请求是独立的。来自一个请求的查询字符串不会自动出现在另一个请求上。
如果您请求/aboutus
,则没有查询字符串。
如果您要求/aboutus?id=5
,那么就有一个。
如果您想在请求之间共享数据,那么可以考虑会话或cookie。