根据从客户端发送到服务器的数据从服务器检索数据

问题描述

我想从客户端向服务器端发送一个 id(string),并基于该 id,我想从服务器端检索与该 id 对应的其他信息。我使用 Node.js 作为后端。
另外,我尝试在 Internet 上搜索内容,但找不到解决方案。希望这不是一个愚蠢的/已经问过的问题。

解决方法

从前端向后端发送内容并获得响应是您可以使用 Vanilla JS fetch api 做的事情。

这是一个例子:

// Here,I'm making a request to an api with the following url:
const URL = 'https://jsonplaceholder.typicode.com/todos'
const ID = 1

fetch(`${URL}/${ID}`)
  .then(res => res.json()) // parse the received information into json
  .then(json => console.log(json)) // print the json

fetch api 正在向 url 发出请求并收到相应的响应。您可以查看 MDN 文档以了解更多详细信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API


假设您在后端使用 NodeJS + Express,您必须设置某种路由。这是一个非常简单的快速服务器示例。

// bring express into your server file
const express = require('express')

// if your front and back end run on different servers,you might need
// to worry about CORS,so you can also bring that in.
const cors = require('cors')

// initialize your application
const app = express()

// take care of cors problem by adding middleware
app.use(cors())

// let's say you have some user data in an array:
const users = [
    {
        id: 1,name: "John"
    },{
        id: 2,name: "Bill"
    }
]

// create your routes.  I'll just make one as an example.
// This route expects to receive a parameter as an id.  The URL
// would look like this: http://yourwebsite.com/123,where 123 is
// the id.
app.get('/:id',(req,res) => {
    // get the id from the req.params object
    const { id } = req.params

    // do whatever you want with id. maybe fetch data from database
    // by id.  Here,we can just take data from users array.
    // We have to turn id into a Number,since params are strings 
    // by default.
    const foundUser = users.find(user => user.id === Number(id))

    // then we can return the user
    res.send(foundUser)
})

// finally,make sure your app is listening for incoming requests 
// on some port.  I'll just use port 3000 and make the server 
// console log a message if there are no errors.
app.listen(3000,console.log('Server listening on port 3000'))

如果您正在讨论如何从服务器向另一台服务器发出请求,您可以使用像 axios 或 node-fetch 这样的 npm 包。

const fetch = require('node-fetch')

// then you can make a fetch request the same way it was done on the 
// front end

fetch('https://github.com/')
    .then(res => res.text())
    .then(body => console.log(body));

话虽如此,我强烈建议你去 youtube 或查看官方的 NodeJS/Express 文档,这样你才能真正了解需要做什么。