首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用导入.js或.mjs文件

使用导入.js或.mjs文件
EN

Stack Overflow用户
提问于 2022-07-30 11:21:26
回答 1查看 299关注 0票数 1

我安装了Node.js并希望运行一个and服务器,该服务器将显示一个从其他.js文件导入javascript函数的html+javascript页面。安装Node.js、运行went服务器和在本地托管一个文件都非常顺利。但是,我一直在访问想要从test_functions.html导入的其他test_functions.html文件时遇到问题。我一直在关注各种在线教程,看看堆栈溢出,尝试了几种不同的方法,但无法让它发挥作用。我想我可能需要调整server.js文件中的某些内容,以允许浏览器访问我想要导入的其他文件?使用.mjs扩展(而不是.js),我的浏览器可以识别我想要导入的函数,但它仍然无法导入我在这些.mjs文件中定义的函数。

以下是server.js的代码

代码语言:javascript
运行
复制
// use the http library to start the node server
const { read } = require('fs')
const http = require('http')
// additional library for file handling
const fs = require('fs')
// port we want to use
const port = 3000
// filename of the html page we want to show when accessing the server
const file_name = 'test_functions.html'
// create the server

const server = http.createServer(function(req, res){
    // tell the brower we will be writing HTML
    res.writeHead(200, {'Content-Type':'text/html'})
    fs.readFile(file_name, function(error, data){
        if(error){
            res.writeHead(404)
            read.write('Error: File ' + file_name + ' not found')
        } else{
            res.write(data)
        }
        res.end()
    })
})
server.listen(port, function(error){
    if (error){
        console.log('Something went wrong', error)
    }
    else {
        console.log('Server is istenng on port ' + port)
    }
})

我的主页test_functions.html如下所示

代码语言:javascript
运行
复制
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <script src="test.mjs" type="module">
        </script>
    </head>
    <body>
        <p>Hey, click on the button below to invoke the function</p>
        <input type = "button" onclick = "showAlert()" value = "Click Me">
    </body>
</html>

虽然我在test.mjs中放置的函数如下所示

代码语言:javascript
运行
复制
export default function showAlert()
{
    alert("welcome");  
} 
console.log('hello')

在以各种方式尝试之后,浏览器一直给我以下两个错误:

  • 未能加载模块脚本:需要一个JavaScript模块脚本,但服务器响应时使用了MIME类型的"text/html“。根据HTMLInputElement.onclick

规范,对模块脚本实施严格的MIME类型检查。

  • 未定义的ReferenceError: showAlert未在HTML规范中定义。
EN

回答 1

Stack Overflow用户

发布于 2022-08-13 16:14:44

为了允许节点服务器在公用文件夹中搜索浏览器请求的所有文件,我遵循以下教程:https://youtube.com/watch?v=gvbVjJnv-b8

最后,通过更新server.js文件,我完成了所有工作,如下所示:

代码语言:javascript
运行
复制
// use the http library to start the node server
const { read } = require('fs')
const http = require('http')

// additional libraries for file handling
const url = require("url");
const fs = require('fs')
const lookup = require("mime-types").lookup;

// server settings
const PORT = 3000
const DEFAULT_PAGE = index.html

// create the server
const server = http.createServer((req, res) => {
    // handle the request and send back a static file from a local folder called 'public'
    let parsedURL = url.parse(req.url, true);
    // remove the leading and trailing slashes
    let path = parsedURL.path.replace(/^\/+|\/+$/g, '');
    if (path == ""){
        path = DEFAULT_PAGE;
    }
    console.log(`Requested path ${path} `);

    let file = __dirname + "/public/" + path;
    // async read file function uses callback
    fs.readFile(file, function(err, content){
        if(err){
            console.log(`File Not Found ${file}`);
            res.writeHead(404);
            res.end();
        } else {
            //specify the content type in the response
            console.log(`Returning ${path}`);
            res.setHeader("X-Content-Type-Options", "nosniff");
            let mime = lookup(path);
            res.writeHead(200, { "Content-type": mime });
            res.end(content);
        }
    });

})
server.listen(PORT, function(error){
    if (error){
        console.log('Something went wrong', error)
    }
    else {
        console.log('Server is istenng on port ' + PORT)
    }
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73175153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档