我无法发出 GET 请求

问题描述 投票:0回答:1

我有一张桌子,下面有一个按钮。该按钮将打开一个表格以填写数据。我是这样做的:

<!--Actually the button calling the form and the table-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mine_contract</title>
    <link href="new.css" rel="stylesheet"/>
    <script src="script.js" defer></script>
</head>
<body>
    <table id="mine_info">
        <tr>
            <th>№</th>
            <th>Number</th>
            <th>Name</th>
            <th>Address</th>
            <th>Full name of the director</th>
            <th>Phone number</th>
        </tr>
        <tr>
            <td><p>1</p></td>
            <td><p>1</p></td>
            <td><p>Example name</p></td>
            <td><p>Example address</p></td>
            <td><p>Full name director</p></td>
            <td><p>+00000000000</p></td>
        </tr>
    </table>
    <div class="popup">
        <div class="popup__container">
            <div class="popup__wrapper">
                <div id="wrapper">
                    <form action="(I don't understand if there should be something here)" method="POST" class="form">
                    <button class="exit" class="exit" id="closeButton" onclick="delRow()">х</button>
                    <div class="string">
                        <label for="id">№:</label>
                        <input type="number" id="id" name="id" required>
                    </div>
                    <div class="string">
                        <label for="N_m">Number:</label>
                        <input type="text" id="N_m" name="n_m" required>
                    </div>
                    <div class="string">
                        <label for="name">Name:</label>
                        <input type="text" id="name" name="name_m"  required>
                    </div>
                    <div class="string">
                        <label for="Adr">Address:</label>
                        <input type="text" id="Adr" name="Adr_m" >
                    </div>
                    <div class="string">
                        <label for="Full_name">Full name of the director:</label>
                        <input type="text" id="Full_name" name="director" required>
                    </div>
                    <div class="string">
                        <label for="Phone">Phone number:</label>
                        <input type="tel" id="Phone" name="Phone_number" placeholder="Например +00000000000" required>
                    </div>
                        <button type="submit" name = "submit" id="contact">Send to DB</button>
                    </form>
                </div>
            </div> 
        </div>
    </div>       
    <button id="button" class="button" onclick="addRow()">Open the form</button>
</body>
</html>

我还编写了一个脚本,用于在单击“发送到数据库”按钮时打开和关闭 POST 请求心轴表单。

//script.js
const button = document.querySelector('#button');
const closeButton = document.querySelector('#closeButton');
const form = document.querySelector('.form');
const popup = document.querySelector('.popup');

button.addEventListener('click', () => {
  form.classList.add('open');
  popup.classList.add('popup_open');
});

closeButton.addEventListener('click', () => {
  form.classList.remove('open');
  popup.classList.remove('popup_open');
});
form.addEventListener('submit', async(e) => {

  e.preventDefault();

  const data = Object.fromEntries(new FormData(form).entries());
  
  try {
    const response = await fetch('http://my_data:3000/mine_info/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    /*const request = await fetch('http://my_data:3000/mine_info/', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
    request: request.json(),
    })Attempt to make a GET request*/

  } catch (error) {
      
    // show some error message in the DOM
    console.log('err: ', error);
  }

  form.classList.remove('open');
  popup.classList.remove('popup_open');
});

我也有一个后端,我是这样做的:

const Pool = require('pg').Pool
const pool = new Pool({
  user: '',
  host: '',
  database: '',
  password: '',
  port: 5432,
})

const getMineinfo = (request, response) => {
    pool.query('SELECT * FROM mine_info', (error, results) => {
       if (error) {
         throw error
    }
    response.status(200).json(results.rows)
     })
}

const createRow = (request, response) => {
    const { n_mine, name_mine, adress, full_name_of_direcor, phone_number } = request.body
  
    pool.query('INSERT INTO mine_info (n_mine, name_mine, adress, full_name_of_direcor, phone_number) VALUES ($1, $2, $3, $4, $5) RETURNING *', [n_mine, name_mine, adress, full_name_of_direcor, phone_number], (error, results) => {
      if (error) {
        throw error
      }
      response.status(201).send(`User added with ID: ${results.rows[0].id}`)
    })
  }

module.exports = {
    getMineinfo,
    createRow,
}//Variables from another file
//another file in which, there are these variables
const express = require('express')
const bodyParser = require('body-parser')
const db = require('./queries')
const cors = require('cors')
const app = express()
const port = 3000

app.use(bodyParser.json())
app.use(
 bodyParser.urlencoded({
    extended: true,
  })
)

app.get('/', (request, response) => {
    response.json({ info: 'Node.js, Express, and Postgres API' })
})

app.use(cors())

app.get('/mine_info', db.getMineinfo)
app.post('/mine_info', db.createRow)

app.listen(port, () => {
    console.log(`App running on port ${port}.`
)})//it works I get the data in the form of JSON by reference http://my-data:3000/mine_info/

为什么我需要 GET 请求才能获取链接上“重要”的数据。但我不明白如何在 POST 旁边放置 GET 请求(例如,在我的例子中,页面加载后立即运行请求不是更正确吗?)。也许我发出 GET 请求的尝试是正确的,但我不明白我需要在那里输入一个循环来呈现表的新行?

我弄清楚了如何发出 POST 请求。它可以工作(将信息写入数据库)。但我不知道如何处理 GET 请求(请帮我弄清楚,这是我在前端和后端都尝试的第一个项目。感谢您阅读这么长的问题。

javascript html ajax
1个回答
0
投票

Why do I need a GET request
:因为您希望在加载页面时显示表格中的行,对吗?

  1. 删除表单的
    action
    属性,这会将请求发送到同一页面(html5)。
  2. 您可以在页面加载时执行 GET 调用来呈现行列表,例如:
document.addEventListener("DOMContentLoaded", function() {

// GET Request
// Load rows in the table element

});

现在应该如何工作,在用户提交表单后,页面应该执行 POST 和重新加载,并且将再次调用 GET 请求,以便表加载预期的数据。

© www.soinside.com 2019 - 2024. All rights reserved.