node.js TypeError:路径必须是绝对的,或者指定根目录到 res.sendFile [无法解析 JSON]

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

本文关键字:res sendFile 根目录 JSON 或者 路径 TypeError js node      更新时间:2023-09-26

[添加]所以我的下一个问题是当我尝试添加新的依赖项(npm install --save socket.io(时。JSON 文件也是有效的。我收到此错误:无法解析 json

npm ERR! Unexpected string
npm ERR! File: /Users/John/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR! 
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse 

所以我一直在试图弄清楚为什么这个错误会再次出现。所有文件(HTML,JSON,JS(都在我桌面上的同一文件夹中。我正在使用节点.js和 socket.io

这是我的JS文件:

var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
  res.sendFile('index.html');
});
http.listen(3000,function(){
    console.log('listening on : 3000');
});

这是返回的内容:

MacBook-Pro:~ John$ node /Users/John/Desktop/Chatapp/index.js 
listening on : 3000
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)

错误很明显,您需要在 res.sendFile() 的配置对象中指定绝对(而不是相对(路径和/或设置root。例子:

// assuming index.html is in the same directory as this script
res.sendFile(__dirname + '/index.html');

或指定一个根(用作要res.sendFile()的第一个参数的基路径(:

res.sendFile('index.html', { root: __dirname });

当您传递用户生成的文件路径时,指定root路径更有用,该文件路径可能包含格式错误/恶意部分,如..(例如 ../../../../../../etc/passwd (。设置root路径可防止此类恶意路径用于访问该基本路径之外的文件。

在 .mjs 文件中,我们现在没有__dirname

因此

res.sendFile('index.html', { root: '.' })

尝试添加根路径。

app.get('/', function(req, res) {
    res.sendFile('index.html', { root: __dirname });
});

我使用了下面的代码并尝试显示站点地图.xml文件

router.get('/sitemap.xml', function (req, res) {
    res.sendFile('sitemap.xml', { root: '.' });
});

如果您信任该路径,则 path.resolve 是一个选项:

var path = require('path');
// All other routes should redirect to the index.html
  app.route('/*')
    .get(function(req, res) {
      res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
    });

错误非常简单。很可能原因是您的索引.html文件不在根目录中。

或者,如果它在根目录中,则相对引用不起作用。

因此,您需要告诉服务器文件的确切位置。这可以通过在 NodeJs 中使用 dirname 方法来完成。只需将您的代码替换为以下代码:

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

确保在首页前添加斜杠"/"符号。否则你的路径将变成:rootDirectoryindex.html

而您希望它是:rootDirectory/index.html

如果您正在处理根目录,则可以使用此方法

res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');

但是如果您使用的是文件夹中的路由,那么/Routes/someRoute.js则需要执行以下操作

const path = require("path");
...
route.get("/some_route", (req, res) => {
   res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
});

在 Typescript 中,图标的相对路径:

import path from 'path';
route.get('/favicon.ico', (_req, res) => res.sendFile(path.join(__dirname, '../static/myicon.png')));

它将重定向到index.html on localhost:8080 call。

app.get('/',function(req,res){
    res.sendFile('index.html', { root: __dirname });
});

我通过使用路径变量来解决这个问题。示例代码如下所示。

var path = require("path");
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + '/index.html'));
})

应用程序中的这种配置.js对我来说效果很好:

    //production mode
if (process.env.NODE_ENV === "production") {
  app.use(express.static(path.join(__dirname, "client/build")));
  app.get("*", (req, res) => {
    res.sendFile(path.join((__dirname + "/client/build/index.html")));
  });
}
//build mode
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname + "/client/public/index.html"));
});

不幸的是,在 ES6 中,要访问绝对路径__dir_name,您必须在任何地方输入以下代码:

import { dirname } from 'path';
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

或者使用要使用的函数创建path.js

import { join, dirname } from 'path';
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export { __dirname, join };

并在使用前导入: import { join, __dirname } from './path.js';

发生在

我身上的事情是,在使用 res.sendFile 时,我收到类似于以下内容的控制台消息:"路径必须是 res.sendFile 的绝对或特定根">,因为局部变量__dirname返回相对路径,而是使用 procces.cwd(( 找到我的应用程序根目录并传递托管我的模板的文件夹。也许这不是最好的选择,但目前它对我有用:

import process from "process"
import path from "path";
let templates = path.join(process.cwd(), "src''public''templates")
app.get("/", function(req, res){
  res.sendFile('403.html', {root: templates});
});

只要这样做,它就会解决你的问题。

res.sendFile('index.html', {root: '.'})

解释:

=> 此代码将发送位于服务器根目录中的"index.html"文件,作为发出请求时的响应。

=> 第一个参数是相对于根目录的文件路径,在本例中为"index.html"。第二个参数 { root: '." } 指定应从中提供文件的根目录。

这可以通过另一种方式解决:

app.get("/", function(req, res){
    res.send(`${process.env.PWD}/index.html`)
});

process.env.PWD将在进程启动时在工作目录前面。

我这样做了,现在我的应用程序可以正常工作,

res.sendFile('your drive://your_subfolders//file.html');

您可以考虑在目录上使用双斜杠,例如

app.get('/',(req,res)=>{
    res.sendFile('C:''Users''DOREEN''Desktop''Fitness Finder' + '/index.html')
})