NodeJS js:我在前端调用JavaScript代码,如何在后台使用代码?

bmvo0sr5  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(146)

我是Node的新手。我使用NodeExpress,并编写了一些简单的Html和简单的JavaScript代码。从test.js文件调用JavaScript代码:<script src ="/javascripts/test.js"></script>

我想在Express后端使用test.js代码,所以如果他们用浏览器检查,没有人可以读取代码。如何将代码(test.js)放在后端?你能解释一下如何做到这一点,也许告诉我任何代码写?谢谢大家!
我从终端创建了Express默认项目,然后自动创建了mi文件夹中的文件。有很多默认创建的文件,但我张贴最重要的

test.js

var people;

function func() {
    people = document.getElementById("combobox").value;
    document.getElementById("result").value = people;
}

function stampa() {
    var frase = "My name is" + " " + (people)
    document.getElementById("textarea").value = frase;
    }

index.html

<head>
    <script src="../assets/js/color-modes.js"></script>
    <script src ="/javascripts/test.js"></script>
  </head>
   
  Select :
  <br>
  <select id="combobox">
    <option value=Mike>Mike</option>
    <option value=John>John</option>
    <option value=Sarah>Sarah</option>
 </select>
  
  <input type="text" id="result" name="TextBox3">
  <br> <br>
  <textarea id="textarea" name="tessxtarea" rows="4" cols="50"></textarea>
  <br>  <br>
  <input type="button" name="clickbtn" value="Display Result" onclick="func(), stampa()">
  </body>
</html>

index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

  // aggiunto io
  app.use(express.static(__dirname + '/public'));

module.exports = app;
dy1byipe

dy1byipe1#

基本上,你的HTML就像它一样好。
这里我们的目标是保持生成变量frase的秘密。我们通过将stampa()的内部工作委托给我们在这里使用Express实现的API调用来实现这一点。

test.js

function func() {
    var people = document.getElementById("combobox").value;
    document.getElementById("result").value = people;
}

function stampa() {

    var people = document.getElementById("combobox").value;

    // for testing purposes, instead of "https://the-site-hosting-your-api.com" you may use "http://localhost:3000"
    fetch('https://the-site-hosting-your-api.com/stampa?people=' + encodeURIComponent(people))
      .then(response => response.json())
      .then(data => {
         document.getElementById("textarea").value = data.frase;
      })
      .catch(error => {
           // Handle any errors by putting out an error notice
      });

}

Express后端将看起来像这样。

app.js

const express = require('express');
const app = express();
const port = 3000;

app.get('/stampa', (req, res) => {
    const { people  } = req.query;
    
    res.json({ frase: "My name is" + " " + people });
});
    
// Starting up the server instance
app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});

希望这对你有帮助。

相关问题