繁体   English   中英

如何将对象数组发布到 Node.js 服务器?

[英]How to post an array of objects to a Node.js server?

如何将一组包含用户数据的对象发布到可以验证的服务器上? 我正在尝试从订单中获取数据以传递到服务器进行验证,然后显示在我重定向到的另一个页面上。

const addProducts = (ev) => {
    ev.preventDefault();
    let products = [];
    for(let k = 0; k < counter+1; k++) {

    let bund = 'Bundled' + k;
    let sing = 'Single' + k;
        let unit = 'BundledUnits' + k;
        let name = 'ProductTitle' + k;
        let quant = 'Quantity' + k;
        let lPrice = 'ListPrice' + k;
        let instruct = 'Instructions' + k;

 if(document.getElementById(asin)) {
    if(document.getElementById(bund) && document.getElementById(bund).checked) {
        if(document.getElementById(unit).value) {
            let bundProduct = {
            id: k.value,
                        "Bundled": "true",
                        "Product": document.getElementById(name).value,
                        "quantity": document.getElementById(quant).value,
                        "ListPrice": document.getElementById(lPrice).value,
                        "Instructions": document.getElementById(instruct).value
                    };


                    products.push(bundProduct);
                }
            }

  else if(document.getElementById(sing) && document.getElementById(sing).checked) {
                let singProduct = {
                    id: k.value,
                    "Bundled": "false",
                    "Product": document.getElementById(name).value,
                    "quantity": document.getElementById(quant).value,
                    "ListPrice": document.getElementById(lPrice).value,
                    "Instructions": document.getElementById(instruct).value
                };
               

                products.push(singProduct);
            }
        }
        console.log(k);
    }


    let order = sessionStorage.setItem('order', JSON.stringify(products));

您可以使用fetchaxios类的库。

检查这个问题如何使用 fetch 执行 POST 请求: Fetch: POST JSON data

POST 请求示例 function 与axios

const sendToServer = async (products) => {
    try {
      // store response in variable if needed
      const res = await axios.post(
        "/your_api/products",
        products  // products you want to post
      );
      // return data in case
      return res.data
    } catch (error) {
      console.log(error);
    }
  }
// implement this function where you need it
sendToServer(products)

或查看axios文档中的 POST 示例: https://axios-http.com/docs/post_example

// Send a POST request
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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