项目捆绑在webpack上
这是我的表格
<form class="book-form" method="POST" action="/about.html">
<input type="text" name = 'name'class="padding3" placeholder="Введіть ваше ім'я" />
<input type="text" name = 'phone_number'class="padding3" placeholder="Ваш номер телефону" />
<select class = "select" name="select-films"></select>
<input type="submit" class="button"> </input>
</form>
我需要将此值写入文件。我不知道如何管理默认的 webpack 服务器,所以我制作了外部 Express 服务器,我需要在该服务器上进行请求并使用 fs 模块保存它。我怎样才能做到这一点?
我尝试做请求
const bookForm = document.querySelector(".book-form");
const select = document.querySelector(".select");
const fs = require("fs");
const name = document.getElementsByName('name');
const number = document.getElementsByName('phone_number');
export let fragment = '';
export function abc() {
bookForm.addEventListener("submit", e => {
e.preventDefault();
fragment += name[0].value + ' ' +number[0].value + ' ' + select.options[select.selectedIndex].text;
xhr.open('POST', 'http://localhost:3000', true)
xhr.send(fragment)
xhr.onreadystatechange = function() { // (3)
if (xhr.readyState != 4) return;
if (xhr.status != 200) {
console.log(xhr.status, xhr.statusText)
alert(xhr.status + ': ' + xhr.statusText);
} else {
alert(xhr.responseText);
}
}
});
}
我尝试处理请求。请帮助我
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs')
app.use(express.static(__dirname + '/src'));
urlencodedParser = bodyParser.urlencoded({extended: false})
app.get('localhost:9000/about', function(req, res){
console.log(req.body);
console.log(res.body)
const sth = `${req.body.name}\n +${req.body.phone_number}\n `
fs.writeFile('text.txt', sth, (err)=> {throw err})
}
)
app.listen(3000)
最佳答案
<div class="book-form">
<input type="text" name='name' id="name" class="padding3" placeholder="Введіть ваше ім'я" />
<input type="text" name='phone_number' id="phone_number" class="padding3" placeholder="Ваш номер телефону" />
<select class="select" name="select-films"></select>
<input type="button" class="button" id="submitBtn" />
</div>
<script>
$("#submitBtn").click(function () {
$.post("http://localhost:9000/about",
{
name: $('#name').val(),
phone_number: $('#phone_number').val()
},
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
</script>
关于javascript - 我应该如何向其他本地服务器发出请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58662603/