0

我正在尝试使用 node 为前端应用程序提供服务,只是学习 express 的基础知识。我遇到的问题是我通过 SRC 链接到我的 html 的 javascript 无法访问 DOM。如果 console.log(document) 我可以将整个文档对象视为一个字符串,但是如果我尝试访问其中的任何内容,例如表单或正文,它将返回NULL。null null null null null。例如,console.log( document.getElementById('input') ) 将 null 记录到浏览器,而 console.log(document) 将文档记录到浏览器。我的 css 以同样的方式加载就可以了。为什么是这样?如何绕过它?

路径:天气/src/weather.html

html:

<!doctype html>

<head>
  <title>The Weather</title>
  <meta charset='utf-8'>
  <script type='text/javascript' src='/weather.js'></script>
  <link rel='stylesheet' type='text/css' href='weather.css'/>
</head>
<body>
  <div id='entry'>
    <h1>Weather</h1>
    <form name='add_address' action='#'>
      <input id="input" name='address' type='text' placeholder='Street Address, Zip, State' maxlength='60'>
    </form>
  </div>
</body>

路径:天气/router.js

路由器.js:

 const path = require('path'),
  express = require('express'),
  router = express.Router(),
  bodyParser = require('body-parser'),
  app = express(),
  port = 3000

app.listen(port)

router.get( '/weather', (req, res)=>{
   res.sendFile(path.join( __dirname + '/src/weather.html' ))
})
router.get( '/weather.css', (req, res)=>{
  res.sendFile(path.join( __dirname + '/src/weather.css' ))
})

app.get('/weather.js', (req, res) => {
  res.sendFile(path.join( __dirname + '/src/weather.js'))
})
app.use('/', router)
4

1 回答 1

0

@乔治·贝利。谢谢。脚本在 DOM 加载之前运行。我猜需要复习一些基础知识。

<head>
  <title>The Weather</title>
  <meta charset='utf-8'>
  <link rel='stylesheet' type='text/css' href='weather.css'/>
</head>
<body>
  <div id='entry'>
    <h1>Weather</h1>
    <form name='add_address' action=''>
      <input id="input" name='address' type='text' placeholder='Street Address, Zip, State' maxlength='60'>
    </form>
  </div>
</body>
<footer>
  <script type='text/javascript' src='./weather.js'></script>
</footer>
于 2018-05-08T07:18:56.060 回答