Seppo
Seppo

Reputation: 177

Basic function call in node.js

If I write following code, I get "Hello World", but not "Hey from function". What am I doing wrong? Same if I try to write to console from called function. Seems it is not called.

This is very basic testing of node.js

const http = require('http');
const express = require('express');

const app = express();

const port = 3000;

function writetest(req, res) {
    res.send("Hey from function");
}


app.get('/nodejs/', function(req, res) { 
    res.send('Hello World!');
    writetest(req,res);
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

No error messages, it just seems not to call he function.

Upvotes: 0

Views: 53

Answers (3)

Rami Jarrar
Rami Jarrar

Reputation: 4643

Use res.write() and you have to call res.end() at the end.

Because res.send() calls res.end() internally and you can't write to res anymore

Upvotes: 3

Arjun
Arjun

Reputation: 1342

You cant executeres.send twice in one api call.You can use if else loop to do such operation but at the same time two res.send cant execute.

Upvotes: 0

Samuel Cooper
Samuel Cooper

Reputation: 552

res.send can only be called once, once the data is sent, the users browser is not waiting for any more responses. What you are trying to achieve can be done with res.write and res.end, detailed here. An example of how to use it is shown here.

Upvotes: 2

Related Questions