簡體   English   中英

調用時未加載 JavaScript 文件<script> tag from html

[英]JavaScript file is not loaded when called in <script> tag from html

我對此很陌生,我不明白為什么我的腳本沒有從 html 加載......這是我的主要問題。

比,我想獲取可用 COM 端口的列表並將某些內容發送到可用端口。 我安裝了串口 v 6.1.1。 我用標簽創建了 index.html 但似乎沒有工作(加載)。 當這工作時,我想在 html 上獲取表單以獲取並將數據(輸入文本)傳遞給 received.js。 js 文件中可能存在錯誤,但無法判斷,因為沒有加載任何腳本。

控制台返回錯誤:

SyntaxError: expected expression, got '<'    [Learn More] index.js:1
SyntaxError: expected expression, got '<'    [Learn More] received.js:1

起點是 server.js:

var http = require('http');
var fs = require('fs');
var http_IP='127.0.0.1';
var http_port = 9876;

//generate html
function onRequest(request, responce){
  responce.writeHead(200,{'Content-type': 'text/html'});
  fs.readFile('./index.html', null, function(error, data){
   if(error){
      responce.writeHead(404);
      responce.write('File not found');
   }else{
     responce.write(data);
   }
    responce.end();
 });

}

http.createServer(onRequest).listen(http_port);
console.log('listening on http://' + http_IP + ':' + http_port);

index.js(警報或控制台也不打印消息)

console.log("Hello");
alert('Hello');

var serialport = require('serialport');

// list serial ports:
serialport.list(function (err, ports) {
  ports.forEach(function(port) {
    console.log(port.comName);

  });
});

serialport.list((err, ports) => {
  console.log('ports', ports);
  if (err) {
    document.getElementById('error').textContent = err.message
    return
  } else {
    //var port = new serialport('"FTDIBUS\VID_0403+PID_6001+FT9PQV36A\0000"', { baudRate: 115200})
    document.getElementById('error').textContent = message
  }

  if (ports.length === 0) {
    document.getElementById('error').textContent = 'No ports discovered'
  }

  const headers = Object.keys(ports[0])
  const table = createTable(headers)
  tableHTML = ''
  table.on('data', data => tableHTML += data)
  table.on('end', () => document.getElementById('ports').innerHTML = tableHTML)
  ports.forEach(port => table.write(port))
  table.end();

});

索引.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>My Serial Port v1</title>
</head>
<body>
  <h3 id="h3">Serial Port v1</h3>

  <FORM class="form" NAME="myform" ACTION="" METHOD="POST" onsubmit="return false">Enter command to process (without "()"): <BR>
      <INPUT TYPE="text" NAME="inputbox" id ="inputbox" VALUE="">
      <INPUT TYPE="button" NAME="button" id = "send_button" Value="Click" onClick="">
  </FORM>

  <script type"text/javascript" src="index.js"></script>   

    <script src="received.js">
    </script>


</body>
</html>

收到.js

const serialport = require('serialport');

var ready ='';


const portName = 'COM20';
var port = new serialport(portName, { parser: serialport.parsers.readline('\r\n'), baudRate: 19200});


//**** SENDING

port.open(function(err){
  if(err){
    return console.log('Error opening port: ', err.message);
  }


  var button = document.getElementById('send_button');
  var form = document.getElementsByName('myform');
  console.log("")

  // var value= '';

  // handling html form
  button.onclick = function myFormHandler(){

    var value = button.form.inputbox.value;

    console.log('Entered value: ', value);
    // storing entered value
    localStorage.setItem('command_value', value);
    command_optics = value;
    console.log('Value of value', value);
    console.log('Value of command_optics', command_optics);
    // recalling entered value
    var command_optics =  localStorage.getItem('command_value');
    console.log('command_optics: ', command_optics);
    // clearing local storage from previous input
    localStorage.clear()
    //  sending command inputted into form textbox
    var sent_data = '(' + command_optics.toUpperCase() + ')\r\n';
    var received_raw_data;

// sending data over COM port
      port.write(sent_data, function(err){
        if(err){
          return console.log('Error on write', err.message);
        }
        console.log('Port.write: ', sent_data);
      }
    );
  }

  //****RECEIVING

// receiving data from COM port
  port.on('data', function(data){

    // raw data passed to var received_raw_data for displaying in html
    received_raw_data = data;

    //trim 'C:', 'R:', 'L:' from string
    // data = data.replace('CRL:','')
    if(data.length > 50){
        data = data.slice(2);
    }

    console.log('Data received (raw): ', data);
    // document.getElementById('data_from_optics').textContent = data
    // writing data from optics module into html
    document.getElementById('data_from_optics').textContent = received_raw_data;
  });

  // Read data that is available but keep the stream from entering "flowing mode"
  port.on('readable', function () {
    console.log('Data2:', port.read());
  });

});

查看您的 HTTP 服務器:

 function onRequest(request, responce){ responce.writeHead(200,{'Content-type': 'text/html'}); fs.readFile('./index.html', null, function(error, data){ if(error){ responce.writeHead(404); responce.write('File not found'); }else{ responce.write(data); } responce.end(); }); }

所以…

  1. 瀏覽器要求index.js
  2. 服務器說“好的!這是一些 HTML”
  3. 服務器輸出index.html的內容

您需要注意瀏覽器請求的是哪個文件,並將其提供給他們,而不是總是發送index.html

由於您發送的是瀏覽器 HTML 而不是 JavaScript,因此當它在 HTML 開頭看到<並嘗試將其視為 JavaScript 時會引發錯誤。


然后看看index.js ...

 alert('Hello'); var serialport = require('serialport');

alert是一個瀏覽器功能,因此如果您在瀏覽器中執行它,它將運行良好。

但是需要串行端口庫? 那不會在瀏覽器中運行。 這取決於節點。

當我在<script> tag

[英]My JavaScript file is not being called by the HTML file when I specify the type as module in the <script> tag

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM