节点.js中的表单处理

Form handling in Node.js

本文关键字:表单 处理 js 节点      更新时间:2023-09-26

一直在学习 Node.js到目前为止,构建了一些 MVC 应用程序,但仍然无法正确处理表单,我需要一些帮助来弄清楚事情是如何工作的。

好的,弄清楚这个东西是如何工作的最好方法是关于我之前的问题,Steam Web API 编程。

我安装了 Express 和 steamwebapi。我的索引.html如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Steam</title>
</head>
<body>
<form action="/ask_user_id" method="POST">
    <input type="text" name="id"><br>
    <input type="submit" value="Pošalji">
</form>
</body>
</html>

我的应用.js

    //Express
var express = require('express');
var server = express();
//Steam
var SteamWebAPI = require('steamwebapi').SteamWebAPI;
SteamWebAPI.setAPIKey('xxx key is here ');
//Rendering form in index.html file
server.get('/ask_user_id', function(req, res) {
    app.render('form', function(err, html) {
        if(err)
            return res.send(err);
        else
            return res.send(html)
    });
});
//Route for handling form submission
server.post('/user_infos', function(req, res) {
    //Form submitted in req.body, retriving userID
    var _userID = req.body.userId;
    //SteamWebAPI - getRecentlyPlayedGames
    SteamWebAPI.getRecentlyPlayedGames(_userID, 5, function(response) {
        return res.json(response.response.games);
    });
});
//Localhost
server.listen(3000, function() {
    console.log('Server: 3000');
});

我正在使用IntelliJ IDEA。我输入终端节点应用程序.js,服务器:3000。如果我转到我的 index.html 文件,它会将我重定向到 http://localhost:63342/Steam/index.html,如果我在表单中键入内容,它会将我重定向到:http://localhost:63342/ask_user_id,我得到"404 未找到"。

我做错了什么?如果我键入节点应用程序.js然后转到 localhost:3000/ask_user_id,我得到引用错误。有人曾经问我为什么在那里需要应用程序;我不知道,如果我放置服务器,它再次会导致错误。

在您的 html 中,更改为 action="/user_infos"

请求将像这样进行

GET /ask_user_id   <- this is you going to localhost:3000/ask_user_id in browser
POST /user_infos   <- this is you submitting the data to the URL specified in the action attribute of your form.

客户端中的后动作是"ask_user_id"

更改服务器以侦听

server.post('/ask_user_id',

没有服务器.get