zoukankan      html  css  js  c++  java
  • Node.js简易服务器,配合type="module" 实现html文件script标签 ES module引入模块

        相信大家在测试type="module" 在html文件中直接模块化引入 js时,会出现一个跨域问题。

     当我们将<script ></scirpt> 标签type设置为"module" 之后,script 标签就不具备跨域能力了

    自然我们需要将项目托管在一个本地服务里面。下面时一个简单的Node.js 服务

    ```js

    var http = require('http');
    var fs = require('fs');
    http.createServer(function(req, res) {
        if(req.url ==='/favicon.ico') {
            return res.end();
        } // 将默认的浏览器行为过滤。也并无相关
        var f= '/this上下文module模式/1.html';
        if(req.url.match(/.js$/)) {
            f = '/this上下文module模式'+req.url;
            res.setHeader('content-Type','text/javaScript;charset:utf-8')
        } // 核心解决方法 ------
        res.writeHead(200);
            if(req.url === '/2') {
                return fs.createReadStream(__dirname+'/this上下文module模式/2.html').pipe(res)
            }  // 这个时测试另外一个分页,与本篇随笔无关
        fs.createReadStream(__dirname+f).pipe(res);
    }).listen(3000);
    ```js
     
    如果没有核心代码部分,对js访问时的操作,那么就会出现下面这个报错。

     因为项目在服务器上,那么浏览器在请求lib.js的时候,不在时file协议,而是以http协议的方式。我们需要单独对js的请求,进行格式的添加。即

    content-Type: text/javascript  大家又没有发现,这个type其实如果在不是module形势下。时script 默认规定了格式 text/javascript

  • 相关阅读:
    106. Construct Binary Tree from Inorder and Postorder Traversal
    105. Construct Binary Tree from Preorder and Inorder Traversal
    449. Serialize and Deserialize BST
    114. Flatten Binary Tree to Linked List
    199. Binary Tree Right Side View
    173. Binary Search Tree Iterator
    98. Validate Binary Search Tree
    965. Univalued Binary Tree
    589. N-ary Tree Preorder Traversal
    eclipse设置总结
  • 原文地址:https://www.cnblogs.com/yaya666/p/13479786.html
Copyright © 2011-2022 走看看