Node.js HTTP服务器res.end()中HTML代码触发语法错误求助
Node.js HTTP服务器设置text/html时res.end()抛出SyntaxError
刚接触后端开发,在完成本地HTTP服务器作业时遇到问题:当Content-Type设置为text/plain或application/json时服务器正常运行,但设置为text/html时,res.end()中的HTML代码会抛出SyntaxError。已尝试更换引号、格式化文本等操作,问题仍未解决。
相关代码
const http = require('http'); //CREATE A SERVER wth the HTTP variable const server= http.createServer(function(req,res) { //headers //res.writeHead(200,{"Content-Type": 'text/plain'}); //res.writeHead(200,{"Content-Type": "application/json"}); res.writeHead(200,{"Content-Type":'text/html'}); //send back the response information //res.end("wELCOME TO MY zURI INTERNSHIP SERVER!!!"); //res.end('{"name": "Miaro the great", "College": " ESPA Vontovorona, Antananarivo", "Occupation": "Technical support engineer turned software developer"}'); res.end('<html><body style="background:blue; text-align: center; color:orange"> <h1><marquee>Welcome To THIS CLASS YALL</marquee></h1> <p>HOW'S IT GOING?</p> </body></html>'); }); //creating a port server.listen(4000,'localhost'); console.log("GREAT DUDE! YOU HAVE CREATED A SERVER!!!!");
报错信息
D:\dwz\bosyz\zuri\tasks AND RESSOURCES\backend nodejs\wk05\portfolio> node server.js D:\dwz\bosyz\zuri\tasks AND RESSOURCES\backend nodejs\wk05\portfolio\server.js:14 res.end('<html><body style="background:blue; text-align: center; color:orange"> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: Invalid or unexpected token at Object.compileFunction (node:vm:360:18) at wrapSafe (node:internal/modules/cjs/loader:1084:15) at Module._compile (node:internal/modules/cjs/loader:1119:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10) at Module.load (node:internal/modules/cjs/loader:1033:32) at Function.Module._load (node:internal/modules/cjs/loader:868:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:22:47
问题原因及解决方法
核心问题
- 多行字符串语法错误:JavaScript中,单引号或双引号包裹的字符串不能直接换行,你的HTML代码是多行结构,直接写入会触发语法错误。
- 单引号冲突:HTML内容里的
<p>HOW'S IT GOING?</p>包含单引号,而你用单引号包裹整个HTML字符串,会导致字符串提前终止,引发token错误。
解决方式(任选其一)
方式一:使用模板字符串(推荐)
用反引号`包裹整个HTML内容,支持多行书写,内部单引号无需转义:
res.end(`<html><body style="background:blue; text-align: center; color:orange"> <h1><marquee>Welcome To THIS CLASS YALL</marquee></h1> <p>HOW'S IT GOING?</p> </body></html>`);
方式二:拼接多行字符串并转义内部单引号
将每行字符串用+拼接,同时转义HTML里的单引号:
res.end('<html><body style="background:blue; text-align: center; color:orange">'+ '<h1><marquee>Welcome To THIS CLASS YALL</marquee></h1> '+ '<p>HOW\'S IT GOING?</p>'+ '</body></html>');
方式三:用双引号包裹字符串(需转义内部双引号)
若使用双引号包裹整个HTML,需要转义style属性里的双引号,且多行仍需拼接:
res.end("<html><body style=\"background:blue; text-align: center; color:orange\">"+ "<h1><marquee>Welcome To THIS CLASS YALL</marquee></h1> "+ "<p>HOW'S IT GOING?</p>"+ "</body></html>");
内容的提问来源于stack exchange,提问作者Miaro RAKOTOARISOLO
相关产品推荐
相关产品推荐

