将对象从 React 传递到 Express 并创建新的 Airtable 记录

Passing an object from React to Express and creating a new Airtable record

我无法将对象从 React 传递到 Express,然后在 Express 中创建 airtable 记录。

在反应中,我通过以下方式向 Express 发送一个 http 请求:

finalSubmit() {
  const airtableObj = {
    title: 'hi',
  }
  fetch('api/submit',{
    method: 'POST',
    body: JSON.stringify(airtableObj),
    headers: {"Content-Type": "application/json"}
  })
}

我的快递代码是:

app.post('/api/submit', jsonParser, async (req, res) => { 
    const newStudy = JSON.stringify(req.body);   
    await console.log(newStudy); 
    table.create(newStudy, function(err, record) {  
        if (err) {console.log(err); res.json(err)} else {console.log(record), res.json('Success!')}
    });   
}) 

但是,我不断从 airtable 返回错误 api。如果我将 express 代码的第 4 行替换为:

table.create({“title”:“hi”} 

而不是

table.create(newStudy)

,一切正常。看起来这应该根据 airtable 文档工作......(https://airtable.com/api)。我在 JSON 中输入和输出数据的方式有什么问题吗? 谢谢

我找到了一个解决方案,但不确定它是否很好...

app.post('/api/submit', jsonParser, async (req, res) => { 
    table.create({
        "title": `${req.body.post0.title}`} ...

这似乎是因为您正在调用 JSON.stringify(req.body),您不需要这样做。

table.create 需要一个对象,而不是一个字符串,所以你会想做这样的事情:

const newStudy = req.body;
table.create(newStudy, function(err, record) {  
  // ...
});