【问题标题】:I cannot get GET parameters from express [closed]我无法从 express 获取 GET 参数 [关闭]
【发布时间】: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


【解决方案1】:

HTTP 请求是独立的。来自一个请求的查询字符串不会自动出现在另一个请求中。

如果您要求/aboutus,则没有查询字符串。

如果您要求/aboutus?id=5,那么有一个。

如果您想在请求之间共享数据,请考虑使用会话或 cookie。

【讨论】:

  • 好的,所以解决方案是将 fetch('/aboutus') 替换为 fetch(window.location.href),可能会删除 url 的开头,它会起作用,并且可以使用这样的代码?
  • 是的。它必须是fetch('/aboutus?id=5')fetch('/aboutus?id=' + id_value) 或类似的东西。 GET 请求非常简单。如此简单,请求没有什么比这更复杂的了——它都在 URL 字符串中可见
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多