.js文件被html脚本调用时检测为类型:html.即使它的MIME类型("text/html")不



我以前见过这个MIME类型错误,但是我在这里看到的解决方案都没有帮助。

我一直在努力让一个API帖子工作了一段时间,这是我的困惑的最后一个关键,我想。

我有三个文件:

  • Node JS文件:server.js,通过在站点根目录下运行' Node server.js'来运行。
  • HTML文件:index.html
  • Javascript文件:script.js,这是由HTML带来的,正在积极地监听一个按钮被按下

当从HTML文件直接运行这个,它运行良好,但我得到一个CORS错误,这是由于没有通过后端运行它。

当我从Node.js服务器文件中运行它时,它在第一次加载HTML页面时出现以下错误:

The script from “http://localhost:8000/script.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type.
Uncaught SyntaxError: expected expression, got '<' script.js 1:1

我不确定我做错了什么。dev工具中的network选项卡也将script.js称为HTML文件。

index . html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REST API POST</title>
<!-- <link href="styles.css" rel="stylesheet"> -->
<script defer src="script.js"></script>
</head>
<body>
<button target="#post">POST to API</button>
</body>
</html>

server.js:

const express = require('express')
const app = express()
const fetch = require("node-fetch")
const cors = require('cors')
let http = require('http');
let fs = require('fs');
app.use(express.static('public'));
let handleRequest = (request, response) => {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./index.html', null, function (error, data) {
if (error) {
response.writeHead(404);
respone.write('Whoops! File not found!');
} else {
response.write(data);
}
response.end();
});
};
http.createServer(handleRequest).listen(8000);

script.js:

const triggerAPI = document.querySelectorAll('[target]')
triggerAPI.forEach(button => {
button.addEventListener('click', () => {
// const modal = document.querySelector(button.dataset.modalTarget)
postToAPI()
})
})
function postToAPI() {
console.log("this is bleep!")
fetch('https://api.clickup.com/api/v2/list/67541785/task', {
method: 'post',
body:    JSON.stringify(body),
headers: { 'Authorization': 'pk_9326_5JD2PZO42X1XLZI2NCOZL08HIB3YY6DM', 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
}
const body = {
"name": "Test from HTML code :)",
"description": "New Task Description"
};

更新1:

app.use(express.static(''));
app.get('/', (request, response) => {
response.sendFile('index.html')
})
app.listen(8000)

更新2:文件夹设置:

  • 网站(文件夹)
      • index . html
      • package-lock.json
      • package.json
      • script.js
    • server.js

我在做什么?

cd网站节点server.js

发生什么错误?

由于MIME类型(" text/html ")不匹配(X-Content-Type-Options: nosniff),来自" http://localhost:8000/server.js "的资源被阻止。

update 2 server.js文件:

const express = require('express')
const app = express()
const fetch = require("node-fetch")
const cors = require('cors')
app.use(express.static('public'));
app.get('/', (request, response) => {
response.sendFile('/index.html')
})
app.listen(8000)

更新3:

现在,它正在工作,除了它击中:

跨域请求阻塞:同源策略不允许读取远程资源https://api.clickup.com/api/v2/list/6/task。(原因:CORS头' Access-Control-Allow-Origin '丢失).

跨域请求阻塞:同源策略不允许读取远程资源https://api.clickup.com/api/v2/list/6/task。(原因:CORS请求未成功).

script.js:

const openModalButtons = document.querySelectorAll('[target]')
openModalButtons.forEach(button => {
button.addEventListener('click', () => {
const modal = document.querySelector(button.dataset.modalTarget)
postToAPI()
})
})
function postToAPI() {
console.log("this is bleep!")
fetch('https://api.clickup.com/api/v2/list/67541785/task', {
method: 'post',
body:    JSON.stringify(body),
headers: { 'Authorization': 'pk_10219326_5JD2PZO42X1XLZI2NCOZL08HIB3YY6DM', 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
}
const body = {
"name": "Test from HTML code :)",
"description": "New Task Description"
};

Server.js:

const express = require('express')
const app = express()
const fetch = require("node-fetch")
const cors = require('cors')
app.use(express.static('public'));
app.get('/', (request, response) => {
response.sendFile('/index.html')
})
app.listen(8000)

index . html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REST API POST</title>
<!-- <link href="styles.css" rel="stylesheet"> -->
<!-- <script defer src="script.js"></script> -->
<script defer src="script.js"></script>
</head>
<body>
<button target="#post">POST to API</button>
</body>
</html>

你没有正确使用express,不要尝试运行自己的服务器,如果你正在使用express,做一个或另一个

app.use(express.static('public'));

这里你已经告诉express为你提供静态文件,所以只要把。js和。html放在/public中,它就完成了,它会自动工作。静态文件是。html,。js,。css等类似的文件,express路由应该服务于逻辑,而静态文件如。html可以直接服务于服务器请求。通过使用上面的行,你告诉express从/public目录中提供所有静态文件,所以如果你只是把你的。js和。html文件放在那里,你甚至不需要路由。

http.createServer(handleRequest)

这一行也处理每一个请求曾经向服务器,所以当你的。html文件击中客户端的浏览器,它请求。js文件,它将强制它提供。html文件,你已经手动读取磁盘,永远不会提供。js文件。如果你把.js放到/public中,就可以避免这个问题。

app.get('/example', (request, response) => {
response.sendFile('./index.html')
})
...
app.listen(4000)

这是一个如何监听路由以及如何使用express手动发送文件的示例。即使这样也不会执行(我认为),因为。html会在/public中查找html,因为静态声明。

最新更新