javascript - Golang 和 JavaScript 模块
问题描述
我想将 Polymer LitElement 与 Go 后端一起使用。使用 LitElement,我在 JavaScript 模块中实现了 Web 组件!对于服务器端的路由,我像这样使用 Gorilla Mux
mux := mux.NewRouter()
mux.PathPrefix("/").Handler(http.FileServer(http.Dir("./wwwroot")))
这会正确加载静态 html 文件。当 html 文件引用实现 Web 组件的js文件时,我收到以下错误(在 Chrome 中):
加载模块脚本失败:服务器以“text/plain”的非 JavaScript MIME 类型响应。根据 HTML 规范对模块脚本强制执行严格的 MIME 类型检查。
当我将组件模块重命名为扩展名为mjs时,文件加载正确,但 LitElement 的模块无法加载并出现相同的错误。由于我对所有第三方 JavaScript 模块的文件扩展名没有影响,我不知道如何解决这个问题。
(我想如果我使用 Polymer 3 而不是 LitElement,我会遇到同样的问题)
有任何想法吗?
更新
这是请求 lit-element.js JavaScript 模块的输出curl
PS C:\Test\Polymer\LitElement> curl http://localhost:8082/node_modules/lit-element/lit-element.js
StatusCode : 200
StatusDescription : OK
Content : /**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* Th...
RawContent : HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Length: 8925
Content-Type: text/plain; charset=utf-8
Date: Thu, 26 Sep 2019 11:38:23 GMT
Last-Modified: Sat, 26 Oct 1985 08:15:00 GMT
/**
* @licen...
Forms : {}
Headers : {[Accept-Ranges, bytes], [Content-Length, 8925], [Content-Type, text/plain; charset=utf-8], [Date,
Thu, 26 Sep 2019 11:38:23 GMT]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 8925
注意内容类型!!!
解决方案
你确定你到达了正确的终点吗?
看那个小例子(你可以在你的主机上试试看)
$ tree
.
├── main.go
└── wwwroot
└── test.js
1 directory, 2 files
$ cat main.go
package main
import (
"net/http"
"github.com/gorilla/mux"
)
func main() {
mux := mux.NewRouter()
mux.PathPrefix("/").Handler(http.FileServer(http.Dir("./wwwroot")))
http.ListenAndServe(":8080", mux)
}
$ cat wwwroot/test.js
$ go run main.go &
[1] 11841
$ curl -v http://localhost:8080/test.js
* Trying ::1:8080...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /test.js HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.65.3
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Accept-Ranges: bytes
< Content-Length: 0
< Content-Type: application/javascript
< Last-Modified: Thu, 26 Sep 2019 12:12:15 GMT
< Date: Thu, 26 Sep 2019 12:15:36 GMT
<
* Connection #0 to host localhost left intact
推荐阅读
- flutter - Flutter - 开始时检查语言
- button - 隐藏/取消隐藏空行按钮
- javascript - 需要构造函数、方法、访问器或属性。src/app/app.component.ts(129,1):错误 TS1128:需要声明或声明
- python - Pipenv 卡住“⠋ Locking...”
- javascript - Luxon:如何忽略特定日期的默认时区
- java - 如何在我的 TextArea 中显示控制台中显示的文本?
- r - H2O 弹性网络 lambda 搜索不会选择最小化验证偏差的 lambda
- swift - 无法将类型“XXX.Protocol”的值转换为预期的参数类型“XXX.Type”
- python - 使用 pyfmi 创建 2 元组作为 fmu 模型的 model.simulate() 的输入时出错
- c++ - 为什么我不能像 someClassObject++5 那样在后缀 operator++ 中使用虚拟参数?