首页 > 解决方案 > 从公共目录中的 js 文件访问函数

问题描述

我在一个名为 的文件夹中有一个 JS 文件public,其中也有我的 CSS 文件。我正在尝试从 JS 文件 ( scripts.js) 访问一个函数,但没有运气。我已经关注了这篇文章(除其他外),但我仍然收到一个错误Error: Cannot find module './scripts.js'。如果有人可以帮助我,那就太好了。

应用程序.js

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var request = require("request");
var scripts = require("/scripts.js");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");

app.use(express.static(__dirname + '/public'));

const apiUrl = "https://api.darksky.net/forecast/"; 
const apiKey = "XXX";

app.get('/', function(req, res){
    res.render("index");
});

app.post('/results', function(req, res){
    var lat = req.body.latitude;
    var long = req.body.longitude;
    request(apiUrl + apiKey + "/" + long + "," + lat, function(error, response, body){
        if (!error && response.statusCode == 200) {
            var data = JSON.parse(body);
            var temperature = scripts.converter(data.currently.temperature)
            res.render("results", {data: data, temperature: temperature})
        } else {
            console.log(response.body);
        }
    });
});

app.get('/results', function(req, res){
    res.render("results");
});

app.listen(3000, function(){
    console.log("Server has started");
})

脚本.js

module.converter = function(cel) {
        var cel = (far - 32) * (5/9);
        return cel;
}

exports.data = module;

标签: javascriptnode.jsexpress

解决方案


您的模块路径错误。试试var scripts = require("./public/scripts.js");吧。

您正在加载/scripts.js,这是一个scripts.js位于您计算机根目录的文件。要在当前目录中加载文件,您可以执行./scripts.js. 在当前目录上方的目录中,它将是../scripts.js.

如果该文件位于当前目录下方的目录中,例如您的情况,它将是“./directoryname/scripts.js”。directorynamepublic你的情况下


推荐阅读