最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js导致错误400错误的请求的原因

运维笔记admin16浏览0评论

node.js导致错误400错误的请求的原因

node.js导致错误400错误的请求的原因

我正在向我的node.js Web应用程序添加一些代码。我添加了此功能,然后抛出了错误400。我通过按Ctrl-Z删除了它,但仍然抛出了错误400。然后,我制作了一个test.js,它是express的最简单实现,仍然收到错误400。这是我的test.js代码:

const app = require("express")();
const http = require("http").createServer(app);
const url = require('url');

app.get("/", function(req, res)
{
    res.sendFile(__dirname + "/test.html");
});

http.listen(3001, function()
{
    console.log("--listening on port 3001");
});

我已经检查以确保我输入的URL正确,端口正确。我认为某些内容已缓存并正在搞砸,因为如果我清除缓存或使用curl,它就会起作用。有什么想法吗?

回答如下:使用process.cwd()代替__dirname,这会导致错误并生成404。process.cwd()将返回初始化节点的目录。它返回您启动node.js进程的绝对路径。

const app = require("express")(); const http = require("http").createServer(app); const url = require('url'); const path = require('path'); app.get("/", function(req, res) { // res.sendFile(__dirname + "/test.html"); res.sendFile(process.cwd() + "/test.html"); }); http.listen(3001, function() { console.log("--listening on port 3001"); });

或您也可以解析__dirname的路径

const app = require("express")(); const http = require("http").createServer(app); const url = require('url'); const path = require('path'); app.get("/", function(req, res) { __dirname=path.resolve(); res.sendFile(__dirname + "/test.html"); }); http.listen(3001, function() { console.log("--listening on port 3001"); });

发布评论

评论列表(0)

  1. 暂无评论