简体   繁体   English

从 POST 请求返回空 object(带节点和 Express 的秘银)

[英]Returning empty object from POST request (mithril w/ Node and Express)

Currently having an issue where a object with null values for all content except ID is returned when trying to complete a POST request from my front end.目前有一个问题,当尝试完成来自我的前端的 POST 请求时,返回的 object 和除 ID 之外的所有内容的 null 值。 I'm also not receiving any error messages in the console.我也没有在控制台中收到任何错误消息。 I've tested my server using Insomnia and everything works as expected with my POST.我已经使用 Insomnia 测试了我的服务器,并且我的 POST 一切正常。 I've also tried taking the body of newEntry out of curly brackets and including headers (even though Mithril's documentation doesn't show using them).我还尝试将 newEntry 的主体从大括号中取出并包括标题(即使 Mithril 的文档没有显示使用它们)。

FrontEnd前端




const setData = formDOM => {

  const formData = new FormData(formDOM);
  console.log("formData", formData)
  const newEntry = {};

  Array.from(formData.entries()).map(entryValue => {
    const key = entryValue[0];
    const value = entryValue[1];

    switch (value) {
      case "false":
        newEntry[key] = false;
        break;
      case "true":
        newEntry[key] = true;
        break;
      default:
        newEntry[key] = value;
        break;
    }
  });

  console.log("new entry", newEntry)

  m.request({
    method: 'POST',
    url: 'http://localhost:5000/santaslist',
    body: {
      newEntry
    }
  }).then((person) => {
    console.log("updated entry", person)
  });
}


const EntryForm = {


  // state
  data: {
    name: "",
    street: "",
    state: "",
    city: "",
    zipcode: "",
    nice: false,
    naughty: false,
    clicked: false,
  },

  // const { name, street, state, city, zipcode, nice, naughty } = data,

  view: (vnode) => (

    <form name="entry-form" id="entry-form">

       ...

      <button
        class="ui-button"
        type="button"
        data-toggle="modal"
        data-target="#exampleModal"
        onclick={() =>
        { setData(vnode.dom)}
        }
      > Add </button>

     ...

    </form >
  ),
};

export default EntryForm;

BackEnd后端

const app = express()
const cors = require("cors")
const pool = require("./db")
const bodyParser = require("body-parser")

// middleware
app.use(cors())
app.use(express.json())//req.body
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
  }))
//ROUTES//

//create a list item (POST)
app.post("/santaslist", async(req,res) => {
    console.log(req.body)
    // console.log(req.headers)
    // console.log(res)
    try {
        const { name, street, city, state, zipcode, naughty, nice } = req.body


        const newListItem = await pool.query("INSERT INTO listitems(name, street, city, state, zipcode, naughty, nice) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",[name, street, city, state, zipcode, naughty, nice])

        res.json(newListItem.rows)
    } catch (err){

        console.error(err.message)
    }
})

"new entry" and "updated entry" console.logs “新条目”和“更新条目”console.logs

Your code is a bit overcomplicated and you're using the wrong method IMO.您的代码有点过于复杂,并且您使用了错误的方法 IMO。 map is for creating a new array with the elements of an existing array transformed. map用于创建一个新数组,对现有数组的元素进行转换。 What you want is forEach .你想要的是forEach

Try this instead.试试这个。

let newEntry = {};

(formData.entries()).forEach(entry => {
  const [key, value] = entry;

  newEntry[key] = value === "true" ? true : false;
})

Update更新

As you specified in your response that the formData.entries() is an object and not an array, it should be noted that you cannot map over an object.正如您在回复中指定的formData.entries()是 object 而不是数组,应该注意的是,您不能在 object 上使用 map。 However, you can do a for loop:但是,您可以执行for循环:

const entries = formData.entries();
let newEntry = {};

for (const key in entries)
  newEntry[key] = entries[key] === "true" ? true : false;
})

I was able to figure out, instead of body I used the data option.我能够弄清楚,我使用了数据选项而不是正文。

m.request({
    method: 'POST',
    url: 'http://localhost:5000/santaslist',
    // body: newEntry,
    data: newEntry
  }).then((person) => {

    // addPersonToList(person)
    console.log("updated entry", person)

  });
}

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

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