【问题标题】:How to handle ajax post request with node.js and without framworks?如何在没有框架的情况下使用 node.js 处理 ajax 发布请求?
【发布时间】:2019-07-28 13:23:23
【问题描述】:

我正在练习没有任何框架(如 jquery、expressJS)的 node js 和 ajax,方法是做一个使用 openweatherapi 提供有关城市天气信息的简单应用程序。 到目前为止,这是我的代码: app.js

    const http = require("http");
    const fs = require("fs");
    const path = require("path");
    const { parse } = require('querystring');


    const server = http.createServer((req, res)=>{
    if(req.url === "/"){
         fs.readFile("index.html", "UTF-8", function(err, data){
         res.writeHead(200, {"Content-Type": "text/html"});
         res.end(data);
         });
     }else if(req.url === "/public/styles.css"){
         var cssPath = path.join(__dirname + req.url);
         var cssFileStream = fs.createReadStream(cssPath, "UTF-8");
         res.writeHead(200, {"Content-Type": "text/css"});
         cssFileStream.pipe(res);
     }else if(req.url === "/public/main.js"){
         var jsFileStream = fs.createReadStream(`${__dirname}/${req.url}`, "UTF-8");
         res.writeHead(200, {"Content-Type": "text/js"});
         jsFileStream.pipe(res);
     }else if(req.url === "/favicon.ico"){
         res.statusCode=204;
         res.end();
    };
     if(req.url ==="/"&&req.method==="POST"){
         let body = "";
         req.on('data', chunk=>{
             body += chunk.toString();
         });
         req.on("end", ()=>{
             parse(body);
         });
         console.log(body);
     };

  });

  var PORT = process.env.port || 3000;
  server.listen(PORT);
  console.log(`Server listening on port ${PORT}`);

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Weather Application</title>
        <link href="./public/styles.css" rel="stylesheet" type="text/css"/>
        <script src="./public/main.js"></script>
    </head>
    <body>
        <div class="weather-div">
            <h1> Search for weather information of a city</h1>
            <form method="post" action="/">
            <input class="locationName" id="cityName" name="city" type="text" placeholder="City" required/>
            <input class="locationName" id="countryName" name="city" type="text" placeholder="Country"/>
            </form>
            <button id="submitBtn" type="submit">Search Weather</button>
        </div>
    <body>
</html>

main.js

function getData(){
    var city = document.getElementById('cityName');
    var country = document.getElementById('countryName');

    if(city.value.length>0){
    const apiKey = "APIKey";
    const apiUrl =  "http://api.openweathermap.org";

    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

        };
    };
    xhttp.open("POST", "app.js",true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(`city=${city}&country=${country}`);
    };
};

window.onload=function(){
    document.getElementById("submitBtn").addEventListener("click", getData, false);
};

所以我想做的是使用 ajax 发送输入的城市名称,因为我尝试使用简单的表单和提交按钮,但它会不断刷新页面。我不想要它。我希望在 app.js 中接收数据以解析它并使用城市的 json 文件过滤其代码,然后将其返回给 main.js 以向 openweathermap 发送 api 调用。 幸运的是,我知道如何做一些简单的事情:解析和 api 调用。但所有其他的东西我完全不知道。当我搜索它时,我只找到使用 jquery 或 express 的解决方案,但我不希望这样,我希望纯 javascript 变得更好。 先感谢您。

【问题讨论】:

    标签: javascript html node.js ajax


    【解决方案1】:

    事件回调中的第一个参数是事件对象。对于表单,要防止默认浏览器行为刷新或导航到操作页面,请使用e.preventDefault()

    所以执行回调 getData 的点击事件如下所示:

    function getData(e){ // First argument of an event callback is the event
        e.preventDefault(); // Prevent default button type submit behavior    
    
        var city = document.getElementById('cityName');
        var country = document.getElementById('countryName');
    
        if(city.value.length>0){
        const apiKey = "APIKey";
        const apiUrl =  "http://api.openweathermap.org";
    
        const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
    
            };
        };
        xhttp.open("POST", "app.js",true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(`city=${city}&country=${country}`);
        };
    };
    

    【讨论】:

    • 我必须将我的输入放在一个带有 action="/" 和 method="post" 的表单中?
    • 编程有多种方法可以做某事。使用当前的标记和属性,似乎所有事情都需要将您的按钮元素附加为&lt;form&gt; 元素的子元素,例如&lt;form&gt; &lt;!-- some other elements.. --&gt; &lt;button id="submitBtn" type="submit"&gt;Search Weather&lt;/button&gt;,以便提交按钮是拥有的,或者如果您愿意,可以“分配”到该表单。
    • 如果我理解得很好,就没有必要把它放在表单标签中。
    • 是的,有多种方法可以做到这一点
    • 非常感谢您的帮助。
    猜你喜欢
    • 2012-09-21
    • 2017-09-15
    • 2018-02-13
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2011-05-03
    相关资源
    最近更新 更多