NodeJS 如何访问后台收发的内容

x33g5p2x  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(112)

如下面发布的代码所示,对于前端部分,我调用了webservice getTIFFForSubsetAsNIRRange/,我想发送body中显示的内容,webservice被成功调用,但我无法获得body发布到它。
如下所示,在后端,我使用了req.data,但它返回undefined
请让我知道如何访问发送到后端的内容

尝试解决

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

字符串
但它会导致一个错误:
UnhandledPromiseRejection警告:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头

前端

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);
});

ogsagwnx

ogsagwnx1#

使用res.json返回JSON数据:

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()
});

字符串
总而言之,您需要:

  • 使用fetch发布JSON请求
  • 在服务器上设置JSON解析器以处理发布的JSON
  • 使用req.body访问发布的数据
  • 使用res.json返回一些JSON数据

相关问题