如何访问后端发布和接收的内容。

huangapple go评论122阅读模式
英文:

How to access contents posted and received to backend

问题

前端代码部分:

如下所示,对于前端部分,我调用了`getTIFFForSubsetAsNIRRange/`的webservice,并希望发送`body`中显示的内容。该webservice成功调用,但无法获取到发送给它的`body`内容。

如下所示,在后端部分,我使用了`req.data`,但它返回`undefined`。

请告诉我如何访问发送到后端的内容。

尝试解决方法:

```lang-js
let data = req.body;
res.send('Data Received: ' + JSON.stringify(data));

但它会导致错误:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client


前端代码:

```lang-js
drawEvt.on('drawend', e => {
    let feature = e.feature;
    let geom = feature.getGeometry();
    let wktformat = new WKT();
    let geoJSONformat = new GeoJSON();
    let wktRepresenation = wktformat.writeGeometry(geom);
    let geoJSONRepresentation = geoJSONformat.writeGeometry(geom);
    this.wktRepresenation = wktRepresenation;
    this.geoJSONRepresentation = geoJSONRepresentation;
    console.info(debugTag, 'drawEvt.on' + 'wktRepresenation:', this.wktRepresenation);
    console.info(debugTag, 'drawEvt.on' + 'geoJSONRepresentation:', this.geoJSONRepresentation);
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ wktRepresenation: this.wktRepresenation }),
    };
            
    fetch('http://localhost:4000/getTIFFForSubsetAsNIRRange/', requestOptions)
        .then(response => response.json())
        .then(data => (this.postId = data.id));
});

后端代码:

app.post('/getTIFFForSubsetAsNIRRange/', async (req, res, next) => {
    console.log(res.send(req.body))
    return 'OK';
});

app.listen(port, () => {
	console.log('listening to port', port);
});

请注意,前端部分的代码中有一个逗号可能是多余的,可以去掉。

英文:

as shown in the code posted below, for the front-end part, I invoking the webservice getTIFFForSubsetAsNIRRange/ and I want to send the contents shown in body the webservice is invoked successfully but i can not get the body posted to it.

As shown below in the back-end side, I used req.data but it returns undefined

Please let me know how to have access to the contents sent to the backend

attempts to solve it

let data = req.body;
res.send('Data Received: ' + JSON.stringify(data));

but it results in an error:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

front-end:

drawEvt.on('drawend', e => {
    let feature = e.feature;
    let geom = feature.getGeometry();
    let wktformat = new WKT();
    let geoJSONformat = new GeoJSON();
    let wktRepresenation = wktformat.writeGeometry(geom);
    let geoJSONRepresentation = geoJSONformat.writeGeometry(geom);
    this.wktRepresenation = wktRepresenation;
    this.geoJSONRepresentation = geoJSONRepresentation;
    console.info(debugTag, 'drawEvt.on' + 'wktRepresenation:', this.wktRepresenation);
    console.info(debugTag, 'drawEvt.on' + 'geoJSONRepresentation:', this.geoJSONRepresentation);
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ wktRepresenation: this.wktRepresenation }),
,
    };
            
    fetch('http://localhost:4000/getTIFFForSubsetAsNIRRange/', requestOptions)
        .then(response => response.json())
        .then(data => (this.postId = data.id));
});

back-end

app.post('/getTIFFForSubsetAsNIRRange/', async (req, res, next) => {
    console.log(res.send(req.body))
    return 'OK'
});

app.listen(port, () => {
	console.log('listening to port', port);
});

答案1

得分: 1

使用res.json发送JSON数据:

app.post('/getTIFFForSubsetAsNIRRange/', async (req, res, next) => {

    console.log('posted wktRepresenation is:\n', req.body.wktRepresenation);

    // 处理req.body.wktRepresenation的操作

    // 发送一些JSON数据
    res.json({ myProperty: 'myProperty value' }); // 应该显示在response.json()中
});

总结一下,你需要:

  • 使用fetch来发送JSON请求
  • 在服务器上设置JSON解析器来处理发送的JSON数据
  • 使用req.body来访问发送的数据
  • 使用res.json来发送一些JSON数据
英文:

Use res.json to send back JSON data:

app.post('/getTIFFForSubsetAsNIRRange/', async (req, res, next) => {

    console.log('posted wktRepresenation  is:\n', req.body.wktRepresenation);

    // do something with req.body.wktRepresenation

    // send back some json
    res.json({myProperty:'myProperty value'}); // should show in  response.json()
});

To summarize, you need to:

  • post JSON request with fetch
  • setup JSON parser on the server to process posted JSON
  • use req.body to access posted data
  • use res.json to send back some JSON data

huangapple
  • 本文由 发表于 2023年7月27日 18:33:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定