-1

I'm using node.js, express, request-promise, and I'm writing a server.js file. In the .then statement, I have res.sendFile(__dirname + '/public/thanks.html'); and it seems not to be doing... well anything. When I inspect using Chrome's dev tools and looking at the network tab, I never receive anything called thanks.html on the client at all. There isn't a problem with rp(slackPost) because I properly receive the message in Slack. console.log('Worked!'); and console.log('sent'); both work perfectly fine. Am I using the res.sendFile() function incorrectly?

Here's the relevant section of my server.js file:

app.post('/contact_us', function (req, res) {
//send input to Slack

// console.log('Working.');
// console.log(req.body);

//sets options to create a POST request (request-promise) to send the stuff to slack
var slackPost = {
    headers: {
        'Content-type': 'application/json'
    },
    method: 'POST',
    uri: 'https://hooks.slack.com/services/API/key/here',
    body: '{\x22text\x22:\x22' + req.body.fname + '\n' + req.body.email + '\n' + req.body.info + '\x22}',
    json: false // Automatically stringifies the body to JSON
};

// console.log('Still working.');

rp(slackPost)
    .then(function (parsedBody) {
        // POST succeeded...
        console.log('Worked!');
        res.sendFile(__dirname + '/public/thanks.html');
        // res.redirect('public/thanks.html');
        // res.json(null);
        console.log('sent');
    })
    .catch(function (err) {
        // POST failed...
        // console.log('Failed :(');
        console.log(err);
    });
});

And here's the script that runs on submit:

function sendToSlack() {
var fname = document.forms["contact"]["fname"].value;
var email = document.forms["contact"]["email"].value;
var info = document.forms["contact"]["info"].value;
var formInput = {
    fname: fname,
    email: email,
    info: info
};

fetch('/contact_us', {
method: 'POST',
headers: {
    'Content-Type':'application/json'
},
body: JSON.stringify(formInput)
})
.then(function(res) {
    window.location.replace('public/thanks.html');
    console.log('Posted');
} )
.catch(function(err) {
    console.log('problem');
} );
}
burnst14
  • 95
  • 2
  • 11
  • "*I never receive anything called `thanks.html` [..]*" – `res.sendFile()` just sends the contents of the file, not its name (unless `Content-Disposition` is used – i.e. `res.download()`). Do you able to see its contents in the response for the request to `/contact_us`? – Jonathan Lonowski Jun 03 '16 at 20:00
  • If you want the file to be requested by name, try `res.redirect('/thanks.html')` in place of `res.sendFile()` (note: assuming you have `express.static()` serving files in `public`). – Jonathan Lonowski Jun 03 '16 at 20:04
  • I cannot see its contents. In fact the only thing that happens is a `fetch` to `/contact_us` that has a `cancelled` tag next to it. That fetch happens in my client-side `js` file to send the user inputs to the server. I don't see anything from the server at all. Immediately after that fetch happens, I receive the "contact_us" page once again, but with the user input appended to the URL. – burnst14 Jun 03 '16 at 20:42
  • 1
    If it's cancelled, then the client stopped waiting for a response. Is the `fetch()` started when a `
    ` is submitted? The form may still be carrying out its normal submission as well, which will interrupt the `fetch()` by leaving the current instance of the page. [You can prevent this through the form's `submit` event](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission) – either `return false` or call `event.preventDefault()`.
    – Jonathan Lonowski Jun 03 '16 at 20:49
  • 1
    @burnst14 so you're making an AJAX request (using fetch) and expect that the HTML is being shown somehow? – robertklep Jun 03 '16 at 20:58
  • 1
    Following up and the above comment, if you are making this request via JS, then you need to handle the HTML response data from the same JS function that made the original request. –  Jun 03 '16 at 21:03
  • 1
    Yeah, @love is right. Alternatively, you can redirect _client side_ to a "thank you" page. – robertklep Jun 03 '16 at 21:24
  • I've add the script that runs on submit. Hopefully this helps you understand what's happening. – burnst14 Jun 06 '16 at 15:17
  • Your form is doing a postback, which is canceling the ajax request. In other words, you're failing to prevent the default action from occurring, and the default action is interrupting your ajax request. – Kevin B Jun 06 '16 at 15:22
  • It doesn't appear as though you need ajax at all in this situation. By removing it and having the form post directly to the endpoint, you can allow the server to perform the redirect and remove a good portion of client-side code. (assuming your server-side endpoint can accept formparams) – Kevin B Jun 06 '16 at 15:25
  • Well I need to protect my API key, so I have to postback so I can process and do the send from the server. Does your solution still work in that case? – burnst14 Jun 06 '16 at 15:32
  • Yes, the apikey would still be on your server only. by "the endpoint" i meant your server endpoint that performs the request to slack. – Kevin B Jun 06 '16 at 15:53
  • Okay so you're suggesting a change to the client side code. How can I do this? Sorry, I'm new to webdev. – burnst14 Jun 06 '16 at 15:58
  • action="/contact_us" and stop listening to the submit/click event. – Kevin B Jun 06 '16 at 16:00
  • @KevinB Okay so I don't know how to receive the params now. And the URL didn't change, only the page content. – burnst14 Jun 06 '16 at 16:28
  • @KevinB, make that an answer and I'll mark it as solution. Working now! Thank you! – burnst14 Jun 06 '16 at 19:13

1 Answers1

-1

Have you tried adding a path.join() to that send? Like this:

var path = require('path');

...

res.sendFile(path.join(__dirname + '/public/thanks.html'));

It may also be that you need your app to use express.static()

Kevyn Quiros
  • 155
  • 1
  • 3
  • 11
  • Can you elaborate on what express.static() does? `path.join()` did not work. – burnst14 Jun 06 '16 at 15:18
  • I looked into it and my file already has express.static() set up. Thanks though. – burnst14 Jun 06 '16 at 15:24
  • What the express.static() middlewre does is that it lets you serve static files such as images, css, html, etc... Now, are you sending any parameters to the static function? You should send the route that leads to your public directory, or the directory that has your static files. Could be something like static(path.join(__dirname + '/public')), – Kevyn Quiros Jun 07 '16 at 15:43