Equivalent to sendFile in restify

Asked

Viewed 144 times

1

I would like to show a page when calling a route on Node using restify

No express use like this:

app.get('/', (req, res)=>{
    res.sendFile(__dirname+'/index.html')
})

What it would be like in restify?

If I try that way

TypeError: res.sendFile is not a function

1 answer

1


You can use the API server-Static-restify for sending static files using the method restify.plugins.serveStatic().

I came to read the documentation, looking for a method similar to Express, but I find that this API is dedicated to serving static files. I think this can help your problem, follow the example:

  const restify = require('restify');

  const server = restify.createServer();

  // exemplo GET para a url: 'localhost:8080/home/'
  server.get('/home/*', restify.plugins.serveStatic({
    'directory': './front-end', // voce colocaria o valor do '__dirname'.
    'default': 'index.html' // arquivo html a ser enviado.
  }));

  const respond = (req, res, next) => {
   res.setHeader("Content-Type", "application/json");
   res.send({ msg: "Mensgem via AJAX!" });
   return next();
  }

  server.listen(8080, function() {
   console.log('Servindo arquivo estaticos na porta: ' + 8080);
  });

In this example, the specified route and directory will serve the file located in ./front-end/home/index.html</b>.

Script in index.html for AJAX call:

<script>
  document.addEventListener("DOMContentLoaded", e => {
    const data = fetch("/api/home", {
      method: "POST"
    }).then(response => {
      response.json().then(data => {
        console.log(data);
      });
    });
  });
</script>

on the API serves-Static-restify .

  • You can send parameters from this code to the page?

  • I believe that because it is a static file upload, the only way this page can receive parameters and through an AJAX call, different from the expressJS where Voce uses an engine to render the view in which Voce passes an object to the res.render() method with the desired parameters. I edited my answer and showed how to make this call AJAX.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.