【发布时间】:2020-11-01 13:47:25
【问题描述】:
我是表达、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(当我获取 /aboutus?id=5 时,我确实得到了 id 参数,但我应该总是从浏览器获取 url 似乎不正确并获取那个...) 我看到有人在使用 CORS,但我不知道是否需要它或最好的方法是什么
【问题讨论】:
-
“当我获取 /aboutus?id=5 时,我确实得到了 id 参数”——嗯。是的。如果您不发送查询字符串,为什么服务器应该能够读取它?
-
好的,所以我认为不正确的事情是好的?我是否应该始终从浏览器获取 url 并在 fetch(getURL()) 之类的 fetch 函数中使用它?因为我认为 express 会自己(以某种方式)获取 url 并且它会工作......
标签: javascript node.js reactjs express