English 中文(简体)
POST, 用于在使用CURL时有效载荷的、但在使用电荷时“衰败”的数据。
原标题:POST for data from RESTful API returns valid string when using CURL, but "decoding failed" when using fetch

I have a simple expressjs proxy server relaying requests to a RESTful API and relaying the responses from that API back. If I use CURL to access it, like so:

curl -s "http://localhost:3000/api/findOne" 
  -X POST 
  -H "Content-Type: application/json" 
  -H "Accept: application/json" 
  -d  { /* request body */ } 

then I get valid JSON back to STDOUT.

但是,如果我试图打上<条码>fetch,那么从Javasend 前端来看,它就是这样:

fetch("http://localhost:3000/api/findOne", {
  method: "POST",
  headers: { "Content-Type": "application/json", Accept: "application/json" },
  body: JSON.stringify(/* request body */),
})
  .then((res) => res.json()) // .text() doesn t work either!
  .then((res) => console.log(res))
  .catch((e) => e);

then I get this error returned from the catch block:

“在此处的影像描述”/</a

最糟糕的是,我有代理服务器,打印了它收到的要求和它提出的从实际的低温反应器中提取的要求,我的确在发出曲线呼吁时产生的产出与发出呼声时所产生的产出之间有分量,而且这些服务器重温i Equal,其性质。 也就是说,代理服务器每次都做同样的事情,就会产生一些错误,使得它无法将结果打上钩,even作为便衣文本<>/em>,这是荒谬的。

我根本无法在互联网上找到这方面的任何东西,有人会把我cl在? 感谢。 我用我的网络发展技能(两年来摆脱 lo路)说一字。

Edit:Okae, 因此,我只想再说几句:现在的情况似乎是,从代理服务器获得的产出Im被压缩,就像在产出流中,与APIC末点的原始产出相比,它只是停止。 难道这会导致无法编码吗? 即便如此,这还是应当作为案文加以区别,尽管由于曲解确实如此,但似乎 Java本可以这样做。 此外,即使在代理服务器(don t)的产出上,也会出现脱编码错误,至少是明显的拖网。 这里的服务器代码(略微 stripped)如下:

import express, { Express, Request, Response } from  express ;
import dotenv from  dotenv ;
import bodyParser from  body-parser ;
import cors from  cors ;

dotenv.config();

const app: Express = express();
const port = process.env.PORT || 3000;
const apikey = ...;
const pathsToProxy =  /api/ ;
const MONGODB_URL = ...;

const corsOption = {
    credentials: true,
    origin: [ http://localhost:8080 ,  http://localhost:3000 ],
};

app.use(cors());

app.use(bodyParser.json());

app.all( /api/* , async (req: Request, res: Response) => {
    const url = req.url.replace(pathsToProxy, MONGODB_URL);

    let headers = new Headers();
    headers.set( Content-Type , req.get( content-type ) ||  application/json );
    headers.set( Accept , req.get( accept ) ||  application/json );
    headers.set( apiKey , apikey!);

    const mongoReq = {
        method: req.method,
        headers: headers,
        body: [ PUT ,  POST ].includes(req.method)
            ? JSON.stringify(req.body)
            : undefined,
    };
    try {
        const mongoRes = await fetch(url, mongoReq);
        mongoRes.body?.pipeTo(
            new WritableStream({
                start() {
                    res.statusCode = mongoRes.status;
                    mongoRes.headers.forEach((v, n) => res.setHeader(n, v));
                },
                write(chunk) {
                    res.write(chunk);
                },
                close() {
                    res.end();
                },
            })
        );
    } catch (e) {
        console.log(e);
        res.status(500).send(e);
    }
});

app.listen(port, () => {
    console.log(`[server]: Server is running at http://localhost:${port}`);
});

我在这里看不出导致产出下降的任何明显情况。

问题回答

Simply calls .json() on response Object to have appropriate body.

I don t see useful reason to chunk data which is returned as whole json from mongodb proxy api.

Solution is following:

     try {
        const mongoRes = await fetch(url, mongoReq);

        const status = mongoRes.status;
        const body = await mongoRes.json();
        
        res.set({
          ...mongoRes.headers,
        });
        res
          .status(mongoRes.status)
          .json(body);
     }
     catch (error) {
         console.error(error);
         res
           .status(500)
           .json({
             message: error.message,
           });
     }
          

P.S.“有效扼制”从《欧洲刑法》中回归,并不意味着它有效 j。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.