2016-03-10 49 views
-1

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

好了,推测这件事情是如何工作的最好办法是在我刚才的问题,蒸汽的Web API编程。

我安装了express和steamwebapi。我的index.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> 

app.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。我输入终端节点App.js,server:3000。如果我转到我的index.html文件,它会将我重定向到http://localhost:63342/Steam/index.html,如果我在表单中键入内容,它会将我重定向到:http://localhost:63342/ask_user_id,并且我得到了“404 Not Found”。

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

+0

无意冒犯,但你应该通过许多网上的Node.js教程一个工作,如果你不知道自己在做什么。然后,一旦它的工作,蒸汽工作。 – thedarklord47

+0

当然,我自己写了一本书,使用Node.js和Express进行Web开发,但是如果我不练习,我该如何学习?我在这几个星期里学到了很多,但这是必不可少的,显然没有太难......或者我错了“回合 – Benjamin

+0

多数民众赞成多好你有一本书。我所说的是,你可以找到很多教程(我确信你的书中有一节)通过如何设置表单。但是,在这一点上,通过集成Steam API来增加复杂性毫无意义。 – thedarklord47

回答

0

后集体诉讼中的客户端是 “ask_user_id”

改变服务器监听

server.post( '/ ask_user_id',

没有server.get

+0

如果我在这种情况下输入我的Steam ID:'76561198190043289',I再次得到错误:404没有找到,url仍然是:http:// localhost:63342/ask_user_id, 但如果我去:localhost:3000/ask_user_id,我得到︰不能GET/ask_user_id – Benjamin

0

在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. 
+0

现在我' m出现错误:ReferenceError:应用程序未定义... :( – Benjamin

+0

用您正在运行的当前代码更新您的问题 – thedarklord47

+0

您调用'app.render()''app.js'的第11行。它应该是'server.render()',因为这就是你在第3行叫你表达应用程序:'var server = express();' – thedarklord47