【问题标题】:How to get data from a url in a https .get()如何从 https .get() 中的 url 获取数据
【发布时间】:2023-03-10 04:24:01
【问题描述】:

我正在尝试使用 node.js、express 和 bodyParser 来响应用户的输入,即在表单中输入的内容。当我console.log(req.body) 它打印{}。如果 url 中没有数据,那将是有意义的,但是有。表单正确提交http://localhost:3000/stmd?symbol=FB。我尝试了JSON.parse(req) 并从那里手动获取我需要的东西,但似乎由于键不是字符串,它无法正确解析它。我只想知道在调用app.get('/stmd' ... 时如何获取symbol = FB。我根本不打算使用 bodyParser,这似乎是最简单的方法。

const https = require('https');
const buffer = require('buffer');
const bodyParser= require('body-parser');
const express = require("express")
let app = express();
app.use(bodyParser.urlencoded({extended: true}));

app.listen(3000, () => {
  console.log("listening on 3000");
});

app.get('/', (req, res) => {
  console.log('connected');
  res.sendFile(__dirname + '/index.html')
})

app.get('/stmd', (req, res) => {
  console.log(req.body)
  //res.redirect('/')
})

这是html表单

 <form id="usrInput" action="/stmd" method="get">
   <input type="text" name="symbol" placeholder="Symbol of Stock. Eg: FB for facebook">
   <button type="submit">Submit</button>
 </form>`

【问题讨论】:

    标签: javascript node.js ajax express https


    【解决方案1】:

    只有 POST 请求将表单数据作为请求正文发送。对于 GET 请求,您不需要正文解析器,只需使用请求的 query 属性即可:

    app.get('/stmd', (req, res) => {
      console.log(req.query)
      //res.redirect('/')
    })
    

    【讨论】:

    • 如果我只解析简单的app.get(... 请求,那么我应该删除正文解析器依赖项吗?
    • 是的,你只需要 POST 请求
    猜你喜欢
    • 2015-09-06
    • 2022-01-26
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2019-07-27
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多