【问题标题】:How should I do request to other local server?我应该如何向其他本地服务器请求?
【发布时间】:2020-02-27 22:48:03
【问题描述】:

项目捆绑在 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)

【问题讨论】:

标签: javascript html node.js express webpack


【解决方案1】:
<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>

【讨论】:

    猜你喜欢
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    相关资源
    最近更新 更多