简体   繁体   中英

How to return body in REQUEST nodejs

I just want to return a body but I get only {} instead real data.

const Ocr = (file,req,response) => {

    const options = {
        method: "POST",
        url: "https://api.aiforthai.in.th/ocr",
        headers: {
            "Apikey": "LgArg8PNY2BiY1cmtFsE1XXN6bP6O903",
            "Content-Type": "multipart/form-data"
        },
        formData: {
            "uploadfile": fs.createReadStream(file)
        }
    };

    request(options, function (err, res, body) {
        if (err) {
            console.log(err)
            return 
        }
        return body //here I want to return
    });

};

And this is my main function that call the top code.

exports.testOcr = async (req, res, next) => {
    try {
        const file = "docs/uploadsNotice/65/กรุงเทพ.jpg"
        const result = await requestOcr.Ocr(file)
        return res.status(200).json({
            data: result,
        });
    } catch (error) {
        next(error);
    }
};

My function is not returning body

Can someone please help me with this?

Are you sure you are using json body-parser as a middle-ware, if not, there won't be a body on req.body .

you can install body-parser via npm: npm install body-parser

and then use the middle-ware as shown below:


    const bodyParser = require("body-parser");
    app.use(bodyParser.json())

for more information check the official express docs here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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