简体   繁体   English

节点发送后无法设置标头

[英]node can't set headers after they are sent

i know this question asked many time before but still i'm struggling to figure this out. 我知道这个问题很久以前就问过了,但我仍然在努力解决这个问题。 i have a set of js files. 我有一组js文件。 first one is index.js 第一个是index.js

app.all('/backend/*/*', function(req, res){ // backend/product/getProduct 
    serviceType = req.params[0]; 
    methodType  = req.params[1];  

    exports.serviceType= serviceType;  
    exports.methodType= methodType;   

    main.checkService()
}); 

in here im extracting the params and call checkService method in main.js file 在这里我提取params并在main.js文件中调用checkService方法

main.js main.js

function checkService(){

    switch(index.serviceType){
        case  'product': 
            product.checkMethod();
            break;

        default :
            console.log('no such service')
    }
}

then it move to product.js file 然后它移动到product.js文件

function checkMethod(){ 

    var methodName = index.methodType,
        res = index.res,
        req = index.req;

    switch(methodName){ 
        case 'samplePost':
            var body = req.body; 
            proHan.samplePost(body,function(data,msg,status){
                sendRes(data,msg,status);
            });
            break;

        default :
            console.log('no such method')
    }

    function sendRes(jsonObj,msg,status){
        var resObj = {
            status : status,
            result : jsonObj,
            message : msg
        }
        res.json(resObj);
    }

first it moves to samplePost method in handler.js once the http req finised executing, callback return the results and call sendRes method and send the json 首先它移动到samplePost的方法handler.js一旦HTTP REQ finised执行,回调返回结果,并呼吁sendRes方法和发送JSON

function samplePost(jsonString,cb){ 
    var res = config.setClient('nodeSample');
    // jsonString = JSON.parse(jsonString);
    res.byKeyField('name').sendPost(jsonString,function(data,msg,status){
        cb(data,msg,status); 
    });
}

to send http req i written a common file. 发送http req我写了一个通用文件。 that is config.js 那就是config.js

function setClient(_cls){ 
  var client = new Client(url);
  return client;
}

function parentClient(url){  
    this.postBody = {
      "Object":{}, 
      "Parameters":{
        "KeyProperty":""
      }
    };


}

function paramChild(){
    parentClient.apply( this, arguments );   

    this.byKeyField = function(_key){
      this.postBody.Parameters.KeyProperty = _key;
      return this;
    } 
}  

function Client(url){
    parentClient.apply( this, arguments ); 

    this.sendPost = function(_body,cb){
      _body = (_body) || {};

      this.postBody.Object = _body;

      var options = {  
          host : 'www.sample.com',
          port : 3300,
          path:  '/somrthing',
          headers: { 
              'securityToken' : '123'
          }
      };

      options.method = "POST";  

      var req = http.request(options, function(response){
        var str = ''
        response.on('data', function (chunk) {
          str += chunk;
        });

        response.on('end', function () {
          cb(JSON.parse('[]'),'success',200)  
        });

      });
      //This is the data we are posting, it needs to be a string or a buffer
      req.on('error', function(response) { 
        cb(JSON.parse('[]'),response.errno,response.code)
      }); 

      req.write(JSON.stringify(this.postBody));
      req.end();
    }
}


paramChild.prototype = new parentClient();  
Client.prototype = new paramChild();   

when i send the first req its work but from then again the server crashes. 当我发送第一个req它的工作,但从那时再次服务器崩溃。 it seems like i can't call res.end method again in a callback method. 好像我不能在回调方法中再次调用res.end方法。 how can i fix this. 我怎样才能解决这个问题。 thank you. 谢谢。

you can't call res.end two times. 你不能两次打电话给res.end。 Here is a simple exemple to deal with callback with a basic node server. 这是一个简单的例子来处理基本节点服务器的回调。

const http = require('http');

const hostname = '127.0.0.1';
const port = 4242;
let something = true;

function callback(req, res) {
    something = !something;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Callback Hello World\n');
}

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  if (something) {
    callback(req, res);
  } else {
    something = !something;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
  }
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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