首页 > 解决方案 > Node JS 很新,我正在尝试发布特定请求,但它让我出错

问题描述

这是我获取数据的功能:

let a = showbtn.addEventListener('click',function(){
    list.innerHTML='';
    fetch('http://localhost:3000/products')
      .then ( response =>response.json())
      .then( data => {
         data.forEach( product => {
            let li =document.createElement('li');
            li.textContent=` ${product.id} - ${product.name} - $ ${product.price} `;
            list.appendChild(li);
         });
      })
})

我的 App.js 看起来像这样:

let express=require('express');
app=express();
//after completing index.html we set index.html as a home page like this by introducing public client folder:
app.use(express.static('public'));
productsArray=[];
//every products must have an id number:
let id=1;
app.use(express.json());

//showing all products:
app.get('/products',(req,res)=>{
    res.send(productsArray);
    

})
//creating ptoducts(posts):
app.post('/products',(req,res)=>{
    let newProduct=req.body;
    newProduct.id=id;
    id++;
    productsArray.push(newProduct);
    res.send('new product created by newProduct=req.body and added to array by push method: Array.push(newProduct)')

    
})

这是我的 HTML 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>shop</title>
</head>
<body>
    <h1>shop</h1>
    <h2>show all products</h2>
    <button class="show-products">show</button>
    <!-- //everyl ist item is a separate product -->
    <ul class="product-list"></ul>

<!-- //.................................................................... -->
    <h2>add product</h2>
    <form  class="add-product-form">

    <p>
        <label for="add-product-name">
            product:
         
        </label>
        <input id="add-product-name" type="text" >
    </p>


    <p>
        <label for="add-product-price">
            price:
         
        </label>
        <input id="add-product-price" type="text"  >
    </p>
 
    <button>add</button>

    </form>
<script src="js/script.js"></script>
</body>
</html>

问题是,当我在 localhost:3000 上打开 chrome 并在产品和价格字段中输入一些内容后,我单击显示按钮,但我得到的结果如下:

1 - undefined - $ undefined

第一个是它的 id,第二个是产品名称,但未定义和价格。我认为价值有问题,但我无法解决这个问题。

先感谢您。

标签: javascripthtmlcssnode.jsweb

解决方案


以快递方式处理 POST 正文时,您需要用户body-parser

http://expressjs.com/en/resources/middleware/body-parser.html

npm install body-parser

var bodyParser = require('body-parser')

来自文档的代码

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

推荐阅读