[英]How to read data from POST, test it with a condition and send a response back
I'm looking for an easy solution to front-end and back-end communication. 我正在寻找一种简单的前端和后端通信解决方案。
I want to write simple JS front-end client where a user can put a number between 1 an 10 000 to guess the number that server has generated. 我想编写一个简单的JS前端客户端,用户可以在其中输入1到10000之间的数字来猜测服务器生成的数字。
So the client job is to send number that user is guessing. 因此,客户端的工作是发送用户正在猜测的号码。 The server should test if
secretNumber
is higher or lower then that provided by the user and it should send back that info. 服务器应测试
secretNumber
是否高于或低于用户提供的密码,并应发回该信息。
For now, my server only sends that secret number. 目前,我的服务器仅发送该密码。 I'm getting it inside my client console, so the connection is working.
我正在客户端控制台中获取它,因此连接正常。
My question is how should I modify my server code to read the number value from request, test it and then send the right response (example -> your number is higher than the secretNumber
)? 我的问题是我应该如何修改服务器代码以从请求中读取数字值,对其进行测试,然后发送正确的响应(例如->您的数字大于
secretNumber
)?
This is my server: 这是我的服务器:
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors());
app.use((request, response, next) => {
console.log(request.headers);
next();
});
app.use((request, response, next) => {
request.secretNumber = Math.floor(Math.random() * 10000) + 1;
next();
});
app.get('/', (request, response) => {
response.json({
secretNumber: request.secretNumber
});
});
app.listen(3001, () => console.log("Listening on 3001"));
Here is my front-end JS code (I'm using axios ): 这是我的前端JS代码(我正在使用axios ):
export function guessNumber(guessValue) {
return dispatch => {
dispatch({ type: GUESS_NUMBER });
axios
.post('/guess', {
isNumber: guessValue,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
};
}
And I was here looking for answer, but maybe I'm to inexperiened and I need some real example... 我在这里寻找答案,但也许我不了解,我需要一些真实的例子...
First you need to persist the secretNumber
between requests. 首先,您需要在请求之间保留
secretNumber
。 At the moment you are generating a new value on each request. 目前,您正在为每个请求生成一个新值。
Assuming just one client using the backend concurrently, you can do this by generating the secretNumber
when the server starts and keep it in memory (assign it to a variable). 假设只有一个客户端同时使用后端,则可以通过在服务器启动时生成
secretNumber
并将其保存在内存中(将其分配给变量)来实现。
Then you can simply use route params to capture the client's guess: 然后,您可以简单地使用路由参数来捕获客户端的猜测:
app.get('/guess/:guess', (request, response) => {
const guess = params.guess;
// compare guess with secretNumber and respond accordingly
});
Alternatively you can use the request's body ( https://expressjs.com/en/4x/api.html#req.body ) instead of route params. 或者,您可以使用请求的正文( https://expressjs.com/en/4x/api.html#req.body )代替路由参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.