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?