简体   繁体   中英

POST request not working -- sending empty objects [NodeJS]

I am building this school project where we have to create out own API in NodeJs and free-choice frontend. I wrote the following code: [In public map] app.js

function getAll() {
    console.log("Get all")
    makeRequest("/poems", "GET")
} 

async function getRandomPoem() {
    const ids = [1, 2, 3, 4, 5, 6, 7]
    const randomId = ids[Math.floor(Math.random() * ids.length)]
    const arrayofPoems = await fetch("/poems/" + randomId, {method: "GET"})
    const data = await arrayofPoems.json()

    const titleBox = document.getElementById("title")
    const authorBox  = document.getElementById("author")
    const textBox = document.getElementById("text")

    titleBox.innerText = data.title
    authorBox.innerText = data.author
    textBox.innerText = data.text
}

function addPoem() {
    event.preventDefault();
    let title = document.getElementById("titleInput").value
    let author = document.getElementById("authorInput").value
    let text = document.getElementById("textInput").value

    let newPoem = [{
        id: 8,
        title: "Aaa",
        author: "Ccc",
        text: "Ddd"
    }]
    makeRequest("/poems/", "post", newPoem)
}


async function makeRequest(url, reqMethod, body) {
    
    const response = await fetch(url, {
      //  headers = { "Content-Type": "application/json" },
        method: reqMethod,
        body:JSON.stringify(body)
    })
    console.log(response)
    const data = await response.json()
    console.log(data)
}

[Here the requests to local server] server.js

const express = require('express');
const { poems } = require('./Poems/poemsArray');
const app = express();
const port = 8080;
const allPoems = require('./Poems/poemsArray')

app.use(express.json())
app.use("/", express.static('public'))


app.listen(port, console.log(`App listening on port ${port}`)) 


//  ----------------   POEMS RESOURCE, All endpoints ------------------ //

// Get all
app.get('/poems', (req, res, next) => {
   res.json(allPoems)
})

// Get specific
app.get('/poems/:id', (req, res, next) => {
   const id = req.params.id
   const onePoem = allPoems.find((poem) => poem.id == id)

   if(onePoem) {
       res.json(onePoem)
   } else {
       res.status(404).json({ status: "Poem not found! "})
   }
})

// Post a poem
app.post('/poems', (req, res, next) => {
   allPoems.push(req.body)
   res.json({ status: "A new poem has been posted!"})
})

[And last, the HTML with the input fields, where the values should be sent with the POST req] index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Poems from outer space</title>
    <script src="app.js"></script>
</head>

<body>
    <div id="container">

        <div id="poem-container">
            <h1 style="color:red;text-align:center;">Poems</h1>
            <p style="text-align: center;">Generate a random poem about space!
                <button onclick="getRandomPoem()">Generate my poem!</button>
            </p>

        <div id="showPoem">
            <h1 id="title"><!-- Title of poem injected --></h1>
            <h2 id="author"><!-- Author of poem injected --></h2>
            <p id="text"><!-- Text of poem injected --></p>
        </div>

        <div id="image-container">
            <!-- INJECTED BY EXTERNAL NASA API -->
            <!-- EXAMPLE IMAGE TO TEST DELETE WHEN API WORKS -->
            <img src="img/apod.jpg" alt="Test Image" width="600px" id="img">
        </div>



    </div>
     
    <div id="form-container">
        <form method="post" action="/poems">
            
                <h1>Send us your poem!</h1>
                <label>Your title:</label> <br>
                <input type="text" requirede name="title" id="titleInput"> <br> 
                <label>Your name:</label> <br> 
                <input type="text" required name="author" id="authorInput"> <br> <br>
                <label>Your poem:</label> <br>
                <input type="text" required name="text" id="textInput" style="width:500px;height:500px">
                <br>
            
                <button type="submit" onclick="addPoem()">Send</button>
        
        </form>
    </div>




    </div>

    
</body>
</html>

In the function addPoem() the let newPoem is for testing purposes. The title, author and text should be coming from the form. Anyone can see what I did wrong?

EDIT: in the makeRequest function the header is commented out, that is because if I leave it in my code, suddenly none of the request work anymore?

Thanks to everybody!

you use headers = which is not valid. try headers: {}. When you get empty object, try logging the request. It is also possible that the body get sended as a string,which express.json() middleware cannot parse the data. As a result, you get empty object.

 async function makeRequest(url, reqMethod, body) { const response = await fetch(url, { headers: { "Content-Type": "application/json" }, method: reqMethod, body:JSON.stringify(body) }) console.log(response) const data = await response.json() console.log(data) }

If you are trying to access postman after a while it can also cause issue while sending body. In my case I had done all changes in API, added router,removed validation etc but at last the culprit was postman as whatever data I was sending, it was showing request.body as {}(empty). After I re-installed postman it worked, I just could felt more joyful. it took my 3-4 hours So you can consider this option as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM