Express-res.send()可以工作一次 [英] Express - res.send() works once

查看:245
本文介绍了Express-res.send()可以工作一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node and Express的新手,我只是想开始使用Express做一些事情,然后遇到了这个问题.

I'm new to Node and Express, I was trying to make something with Express just to get started, then I faced this problem.

第一个res.send()效果很好,但是第二个没有触发.

First res.send() works well, but the second one doesn't fire.

这是我的代码:

var express = require('express'),
    app     = express(),
    fs      = require('fs'),
    visits;


app.listen(8080);

app.get('/', function(req,res) {

    res.send('Hello');

    fs.readFile('counter.txt','utf-8', function(e,d) {

        if (e) { 
            console.log(e);
        }
        else {
            console.log(parseInt(d) + 1);
            fs.writeFile('counter.txt',parseInt(d) + 1);
            res.send('<p id="c">' + ( parseInt(d) + 1 ) + '</p>');
        }

    })
...

发送了"Hello",但没有发送.如果我评论res.send('Hello');,将显示访问者.

'Hello' is sent, but res.send('<p> .. </p>'); isn't. If I comment res.send('Hello');, visitors will be shown.

谢谢.

推荐答案

res.send()仅被调用一次.

尝试以下方法:

app.get('/', function(req,res) {
  var response = 'Hello';
  fs.readFile('counter.txt','utf-8', function(e,d) {
      if (e) {
        console.log(e);
        res.send(500, 'Something went wrong');
      }
      else {
        console.log(parseInt(d) + 1);
        fs.writeFile('counter.txt',parseInt(d) + 1);
        response += '<p id="c">' + ( parseInt(d) + 1 ) + '</p>';
        res.send(response);
      }
  })
});

(或者只是res.send("Hello<p id=..."),但是您明白了:)

(or just res.send("Hello<p id=..."), but you get the point :)

这篇关于Express-res.send()可以工作一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆