0

I used Node.js and Express for the first time to make an API and I am having some issues.
I'm using Node.JS 13.11.0 and Express 4.17.1.
When I try to access 127.0.0.1:4008/api/nbhbdm and append parameters, I receive this error.

_http_outgoing.js:535
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:535:11)
    at ServerResponse.header (/Users/zihangu/Desktop/TZG API/nbhbdm/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/Users/zihangu/Desktop/TZG API/nbhbdm/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/zihangu/Desktop/TZG API/nbhbdm/node_modules/express/lib/response.js:267:15)
    at exports.XMLHttpRequest.httpRequest.onreadystatechange (/Users/zihangu/Desktop/TZG API/nbhbdm/app.js:28:17)
    at exports.XMLHttpRequest.dispatchEvent (/Users/zihangu/Desktop/TZG API/nbhbdm/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:591:25)
    at setState (/Users/zihangu/Desktop/TZG API/nbhbdm/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:610:14)
    at IncomingMessage.<anonymous> (/Users/zihangu/Desktop/TZG API/nbhbdm/node_modules/xmlhttprequest/lib/XMLHttpRequest.js:440:13)
    at IncomingMessage.emit (events.js:315:20)
    at IncomingMessage.Readable.read (_stream_readable.js:508:10) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
Process exited with code 1

The following is my code.

const express = require('express');
const app = express();

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",'3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
  });

app.get('/api/nbhbdm',function(req,res,err){
    console.log(req.query);
    var keyword = encodeURI(encodeURI(req.query.keyword));
    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', "https://suo.im/api.htm?&key=000000000000&expireDate=2030-03-31&url=https://abcdef.cn/?s=" + keyword, true);
    httpRequest.send();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
            var result = httpRequest.responseText;
            console.log(result);
            res.json({"status":"ok","slink":result,"nlink":https://abcdef.cn/?s=" + encodeURI(req.query.keyword)});
        }
        else{
            res.json({"status":"error","slink":"connection error","nlink":https://abcdef.cn/?s=" + encodeURI(req.query.keyword)});
        }
    }
})
var server = app.listen(4008, '127.0.0.1', function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log("Server running at http://%s:%s", host, port);
})

I have seen Error: Can't set headers after they are sent to the client, but I don't think I have tried to send multiple responses to the same request.
Can I know where my code went wrong?

2 Answers2

1

I have seen Error: Can't set headers after they are sent to the client, but I don't think I have tried to send multiple responses to the same request.

You have, you just didn't notice it.

The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.

Source: https://www.w3schools.com/js/js_ajax_http_response.asp

Every time onreadystatechange is triggered and the readyState isn't 4 or the status isn't 200, you try and send a response to the client with res.json(). Since you cannot send several responses to the same request, you get thrown an error.

You'd need your onreadystatechange callback to disregard any readystate that isn't 4, and then act depending on the status of the request:

httpRequest.onreadystatechange = function () {
    if (httpRequest.readyState !== 4)
        return;
    if (httpRequest.status == 200) {
        var result = httpRequest.responseText;
        console.log(result);
        res.json({"status":"ok","slink":result,"nlink":https://abcdef.cn/?s=" + encodeURI(req.query.keyword)});
    }
    else{
        res.json({"status":"error","slink":"connection error","nlink":https://abcdef.cn/?s=" + encodeURI(req.query.keyword)});
    }
}
Azami
  • 2,122
  • 1
  • 12
  • 22
0
const User = require('../models/users')

const mongoose = require('mongoose')

here i am importing mongoose and user Schema it works for me

module.exports = {

      checkAuthenticated:(req,res,next)=>{  // Check User Authentication
        if(req.isAuthenticated()){
            return next()
        }
        res.redirect('/login')
    }

}

// If your checkAuthenticated Function is in a different File So make sure you have imported User Schema and Mongoose

atline
  • 28,355
  • 16
  • 77
  • 113
Rameez
  • 1