是否有隐藏的Javascript文件

时间:2019-06-18 20:11:51

标签: javascript html node.js express

如果我要为localhost根文件提供一个HTML文件,如下所示:

app.get('/', (req, res) => res.sendfile('index.html'))

我可以将Javascript文件添加到浏览器无法查看或触摸的HTML文档中吗? 如果是这样,它是否也可以访问节点api?

我是Express的新手,所以我不知道它是如何工作的。

1 个答案:

答案 0 :(得分:1)

从前端接收参数后,您可以让服务器做一些工作。 DOM中加载的javascript将向服务器发送请求,服务器将完成前端JS未知的工作,然后返回结果。

在服务器上:

app.post('/path', (req, res) => {
    const json = req.body;
    //do work
    const resp = {some: 'data'};
    res.json(resp);
}

在前端

fetch('/path', {
  method: 'post',
  body: JSON.stringify(data),
  headers: { 'Content-type': 'application/json' }
})
.then(res => res.json()) // get json data out of response object
.then(json = > {
    // do something with response json
}

您将需要阅读Express和主体解析,以及在GET请求中使用参数,而不是POST请求中的body和其他类型的请求。

相关问题