【问题标题】:how to format json body sent from axios如何格式化从axios发送的json正文
【发布时间】:2021-10-16 01:00:28
【问题描述】:

这里是 React 初学者,我正在使用 axios 从我的前端表单中发送正文。我在服务器端做了一个console.log,这就是我在request.body 中看到的。

req.body {
  '{"body":"{\\"firstName\\":\\"daf\\",\\"lastName\\":\\"afa\\",\\"address\\":\\"af\\",\\"phoneNumber\\":\\"123-933-6177\\",\\"email\\":\\"asfa\\",\\"facilityName\\":\\"afs\\",\\"isSeller\\":false}"}': ''
}

我在上面打印错误字符串的类

checkIfDuplicateEmailAndFacilityNameOnSignUp = (req, res, next) => {
    // get the customer name
    console.log("request", req.body.firstName);
    const updatedBody = JSON.parse(req.body);
    console.log(updatedBody);
    Customer.findOne({
        where: {
            email: req.body.email
        }
    }).then(customerEmail => {
        if (customerEmail) {
            res.status(400).send({
                message: "This email is already in use"
            });

            return;
        }

        Customer.findOne({
            where: {
                facilityName: req.body.facilityName
            }
        }).then(facilityname => {
            if (facilityname) {
                res.status(400).send({
                    message: "Facility exists already exists"
                });
                return;
            }

            next();
        });
    });
};

这是我从前端发帖的功能

  const onFormSubmit = (event) => {
      event.preventDefault();

  const formBody = {
    ...this.state,
  };

  axios({
    method: "POST",
    url: "http://localhost:3000/api/auth/signup",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
    data: {
      body: formBody,
    },
  }).then((response) => {
    console.log("response", response);
    console.log("response data", response.data);
  });

  console.log("form submission done");
};

状态对象

  state = {
    firstName: "",
    lastName: "",
    address: "",
    phoneNumber: "",
    email: "",
    facilityName: "",
    isSeller: false,
  };

这是我的节点 server.js 文件

const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.json());

app.use(
    cors({
        origin: "*",
    })
);
app.use(
    bodyParser.urlencoded({
        extended: true,
    })
);

require('./app/routes/authRoutes')(app);
require('./app/routes/customerRoutes')(app);

const PORT = 3000;

app.listen(PORT, () => {
    console.log(`Now listening on port ${PORT}`);
});

db.sequelize.sync({
    force: true
})
    .then(() => {
        console.log("Dropping and Resync DB");
        initial();
    });

// creates roles in database for us
function initial() {
    Role.create({
        id: 1,
        roleType: "buyer"
    });

    Role.create({
        id: 2,
        roleType: "seller"
    });
};

我尝试使用 JSON.parse(),但收到消息 Unexpected token o in JSON at position 1 的异常。关于如何解析这个有什么想法吗?

更新 1:

根据@Bravo 回答更改后,身体现在看起来像这样

  body: {
    firstName: 'safds',
    lastName: 'asf',
    address: 'adfs',
    phoneNumber: '404-932-6177',
    email: 'asdf',
    facilityName: 'afs',
    isSeller: false
  }

可能是一个愚蠢的问题,但我如何访问这些字段。我尝试做 body.firstName 或 body[0] 但我得到未定义的返回?

【问题讨论】:

  • Unexpected token o in JSON at position 1 ... 试图传递 string [object Object] 的经典案例 .. 某处的某些东西正在强制一个对象变成一个字符串 - 你不这样做太糟糕了'不显示“我尝试使用 JSON.parse”的位置
  • 现在更新@Bravo
  • 您需要发送数据:作为"Content-Type": "application/x-www-form-urlencoded"的“查询字符串”

标签: javascript node.js json axios


【解决方案1】:
headers: {
    "Content-Type": "application/x-www-form-urlencoded",
},

这就是问题所在。您在编码方面撒谎,所以 Express 通过 bodyParser.urlencoded 而不是 bodyParser.json 运行您的身体。

去掉自定义标题,只使用 Axios 的默认值。

【讨论】:

  • @Bravo — 是的(因为它将传递给正文的对象编码为 JSON,它使用 Content-Type 标头做正确的事情)。
  • 是的,没有选项处理程序,但这是另一个问题,并且包含在 cors 模块手册中。
  • @Bravo — 他们有,但它不是为预检请求设置的。
  • 他们添加该标题以解决飞行前问题的赌注是什么
  • body.firstName 应该可以正常工作……但如果您有新问题,请提出 new 问题。不要将其编辑到现有问题的末尾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 2022-08-16
  • 2021-07-22
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
相关资源
最近更新 更多