【问题标题】:JavaScript file is not loaded when called in <script> tag from html在 html 中的 <script> 标记中调用 JavaScript 文件时未加载
【发布时间】:2018-03-05 11:29:10
【问题描述】:

我对此很陌生,我不明白为什么我的脚本没有从 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();

});

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>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>

received.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());
  });

});

【问题讨论】:

  • 你不能在浏览器中运行server.js,你需要一个node.js 环境。例如在终端中运行node server.js。其余的代码对我来说似乎没问题。
  • 就像@Quentin 解释的你总是返回相同的网站资源,你永远不会从你的 server.js 中返回任何 Javascript。您需要做的是实现某种路由逻辑,这可能很棘手,这也是大多数人使用为您完成这一切的库的原因。例如。 Express 或 KOA.. 等
  • @VladimirJovanović 我正在从 cmd 运行 server.js,除非你的意思不同。
  • 谁投了反对票,你能解释一下原因吗?

标签: javascript node.js script-tag node-serialport


【解决方案1】:

查看您的 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 开头看到 &lt; 并尝试将其视为 JavaScript 时会引发错误。


那就看index.js

alert('Hello');

var serialport = require('serialport');

alert 是一个浏览器函数,所以如果你在浏览器中执行它,它将运行良好。

但是需要串口库?那不会在浏览器中运行。这取决于节点。

【讨论】:

  • 所以如果我发送 ./ndex.js 而不是 /index.html 我摆脱了&lt; 问题,但现在我得到的是 index.js 的纯文本而不是“已处理”的 javascript 文件。如@Keith 所建议的那样,没有快递可以吗?
  • @cheeroke — 把它写成一个函数。调用函数。发送输出。 (但对&lt;script src&gt; 的回复可能没有多大意义)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-06-10
  • 2014-03-29
相关资源
最近更新 更多