简体   繁体   English

从公共目录中的js文件访问函数

[英]Accessing a functions from a js file thats in a public directory

I have a JS file in a folder called public , which also has my CSS file in it. 我在名为public的文件夹中有一个JS文件,其中也有我的CSS文件。 I'm trying to access a function from the JS file ( scripts.js ), but am having no luck. 我正在尝试从JS文件( scripts.js )访问函数,但是没有运气。 I've followed this post (amongst others), but I am still getting an error of Error: Cannot find module './scripts.js' . 我已经关注了这篇文章(以及其他文章),但仍然收到Error: Cannot find module './scripts.js' If anyone can help me out, that would be great. 如果有人可以帮助我,那就太好了。

app.js app.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");
})

scripts.js scripts.js中

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

exports.data = module;

The path to your module is wrong. 模块的路径错误。 Try var scripts = require("./public/scripts.js"); 试试var scripts = require("./public/scripts.js"); instead. 代替。

You are loading /scripts.js , which is a scripts.js file located at your computers root . 您正在加载/scripts.js ,这是位于计算机根目录下scripts.js文件。 To load a file in the current directory, you would do ./scripts.js . 要将文件加载到当前目录中,请执行./scripts.js In a directory above the current one, it would be ../scripts.js . 在当前目录之上的目录中,它将是../scripts.js

If the file is in a directory below the current directory, like in your case, it would be './directoryname/scripts.js'. 如果文件位于当前目录下的目录中(例如您的情况),则为“ ./directoryname/scripts.js”。 directoryname being public in your case 在您的情况下, directorynamepublic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM