ERR_HTTP_HEADERS_SENT节点js套接字连接

时间:2020-10-05 20:19:00

标签: node.js express sockets

我正在构建一个API,该API使用套接字连接与C#内置的服务器后端进行交互。这是我到目前为止所拥有的

const request = require('request');
const express = require('express');
const app = express();
var server = require('http').createServer(app);
var cors = require("cors");
app.use(cors());
const net = require('net');
const client = new net.Socket();
const stringToJson=require('./stringToJson')

const port = process.env.PORT;
const host = process.env.HOST;


client.keepAlive=true

client.on('close', function() {
    console.log('Connection closed');
});

app.get('/getScores',function (req,res) {
    let dataSend=''


    client.on('data', function (data) {
        console.log('Server Says : ' + data);

        if(data!='ANALYSIS-ERROR'){
            dataSend=stringToJson.stringToJson(data)
        }
        else{
            dataSend=stringToJson.stringToJson('0:0.0:0.0:0.0:0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0')

        }
        client.destroy()


        return  res.send(dataSend)


    });
    client.connect(port, host, function () {
        client.write(`GENERAL-ANALYSIS|${req.query.id}|${req.query.website}|`)
        return

    });

    return

})

app.get('/getPlace',function (req,res) {
   console.log(req.query)
    request(
        { url: `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${req.query.name}+in+${req.query.city}&key=${process.env.API_KEY}` },
        (error, response, body) => {
            if (error || response.statusCode !== 200) {
                return res.status(500).json({ type: 'error', message: error.message });
            }

            return res.json(JSON.parse(body));
        }
    )
})


//TODO ADD 404 500 PAGES
app.use((req, res, next) => {
    res.status(404).send("Sorry can't find that!");
});

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});




server.listen(9000, () => {
    console.log(`App running at http://localhost:9000`);
});

基本上,它与服务器建立连接并侦听一些要发送回的数据。然后处理该字符串并将其发送到React前端。 api调用是由前端使用axios进行的 它可以工作,但是如果刷新页面,则会引发此错误 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我该如何解决?

1 个答案:

答案 0 :(得分:0)

尝试按照文档request.setHeader(name, value)

中的设置标题
request.setHeader('Content-Type', 'application/json');