mercadoPago {“错误”:“JSON 格式错误”}

问题描述 投票:0回答:1

所以,我一直在使用以下代码:

    require("dotenv").config();
    const { MercadoPagoConfig, Preference } = require("mercadopago");
    const { Product } = require("../../models/Product"); 
    const { User } = require("../../models/User"); 

    require("../../db"); 

    const ACCESS_TOKEN = process.env.ACCESS_TOKEN;
    const client = new MercadoPagoConfig({ accessToken: ACCESS_TOKEN });
    const payment = new Preference(client);

    const placeOrder = async (req, res) => {
    try {
    
    const cart = req.body;
    console.log(cart);

    let items = cart.map((product) => ({
      title: product.name,
      quantity: product.quantity,
      unit_price: product.price,
      currency_id: product.currency, 
      image: product.img,
      description: product.description,
    }));

    let preference = {
      items: items,
      back_urls: {
        failure: "http://localhost:3001",
        pending: "http://localhost:3001",
        success: "http://localhost:3001",
      },
    };

    const response = await payment.create(preference);
    res.status(200).send(response);
    console.log(response);
    } catch (error) {
    res.status(400).json({ error: error.message });
    }
    };

    const successfulPurchase = async (req, res) => {
    try {
 
    res.status(200).send("Purchase completed successfully");
    } catch (error) {
    res.status(400).json({ error: error.message });
    }
    };

    module.exports = { placeOrder, successfulPurchase };

这段代码以前工作得很好,但后来我在 Thunderclient 和繁荣中再次尝试了它:

{   "error": "Bad JSON format" }

然而 JSON 实际上没问题:

    [
    {
    "name": "Mouse chingon",
    "quantity": 1,
    "price": 165,
    "currency": "MEX",
    "img": "https://i.imgur.com/RdwnTcv.png",
    "description": "Es un mouse bien chingon"
    }
    ]

我一直上下检查,直到打破了我的书和窗户,我不知道该搬到哪里,甚至不知道该搬什么

我已经将 JSON 进行了简化,检查了中间件,继续简化了代码,然后一切都崩溃了,天哪,我在 12 个小时的战斗后泪流满面

json bad-request mercadopago
1个回答
0
投票

更换:

const response = await payment.create(preference);

与:

const response = await payment.create({ body: preference });

这可确保在向

preference
发出请求时,
payment.create
对象的结构正确。您可以在 MercadoPago Node.js SDK 文档

中找到更多详细信息
© www.soinside.com 2019 - 2024. All rights reserved.