gpt4 book ai didi

javascript - Ajax 与表单方法作为 Node.js 中的 post

转载 作者:行者123 更新时间:2023-12-03 05:20:47 25 4
gpt4 key购买 nike

我在使用 Node.js 的表单中遇到 Ajax 问题,我正在开发一个简单的 Node.js 货币转换器应用程序并使用 Ajax 在前端 (HTML) 上填充数据。然而它不起作用,非常感谢任何帮助。谢谢。

最佳答案

1。前端

改变这个

xmlhttp.open("GET","http://localhost:9099/", true); 

xmlhttp.open("POST","http://localhost:9099/", true); 

因为您的后端服务器接受 POST 来获取答案。

2。后端

从底部删除response.endresponse.writeHead,并将其移动到您要计算store的位置。

您的最终代码:

http.createServer(function(request, response) {
switch (request.method) {
case 'POST':
if (request.url === "/") {
var requestBody = '';
request.on('data', function(data) {
requestBody += data;
if (requestBody.length > 1e7) {
response.writeHead(413, {
'Content-Type': 'text/plain'
});
response.end('Request Entity is too large');
}
});

request.on('end', function(data) {
console.log(requestBody);
var formData = qs.parse(requestBody);

var requestBofy = '';

// I renamed the callback parameter to response2
https.get('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml?8f65cd5d1af1727c40d2a89a31c6a0f1', function(response2) {
if (response2.statusCode >= 200 && response2.statusCode < 400) {
response2.on('data', function(data_) {
requestBofy += data_.toString();
});
response2.on('end', function() {
console.log(requestBofy);
parser.parseString(requestBofy, function(err, result) {
console.log('FINISHED', err, result);

var xml = requestBofy;

var parseString = require('xml2js').parseString;
parseString(xml, function(err, result) {
var jFile = JSON.stringify(result);

var parsedResponse = JSON.parse(jFile);
var rateHUF = parsedResponse['gesmes:Envelope']['Cube'][0]['Cube'][0]['Cube'][6]['$'].rate;
var rateINR = parsedResponse['gesmes:Envelope']['Cube'][0]['Cube'][0]['Cube'][22]['$'].rate;
var store = 'No value';
if (formData.vSelectedValue == 'HUF' && formData.vSelectedValue2 == 'INR') {
store = Math.round(formData.vFirstNo * (rateINR / rateHUF));
} else {
store = Math.round(formData.vFirstNo * (rateHUF / rateINR));
}

// Your response should end here
response.writeHead(200, {
"Content-Type": "text/html"
});
response.end('Your Answer: ' + store);

});

});
});
}
});

});
} else {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.end('404 - Page not found');
}

break;
case 'GET':
if (request.url === "/") {

getFileContent(response, 'public/home.html', 'text/html');

} else {
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.end('404 - Page not found');

}
break;

default:
response.writeHead(404, {
'Content-Type': 'text/plain'
});
response.end('404 - Page not found');

}

}).listen(9099);

关于javascript - Ajax 与表单方法作为 Node.js 中的 post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41394561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com