[英]How to handle ajax post request with node.js and without framworks?
我正在通过做一个简单的应用程序来练习节点js和ajax,而没有任何框架(例如jquery,expressJS),该应用程序使用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以将api调用发送给openweathermap。 幸运的是,我知道如何做简单的事情:解析和api调用。 但是所有其他东西我完全不知道。 当我搜索它时,我只找到使用jquery或express的解决方案,但我不希望那样,我希望纯JavaScript变得更好。 先感谢您。
事件回调中的第一个参数是事件对象。 对于表单,为防止默认浏览器行为刷新或导航到操作页面,请使用e.preventDefault()
。
因此,执行回调getData的click事件如下所示:
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}`);
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.