0

In my app.js, I definite a search router

app.use('/search', require('./router/search'))

In the search.js files, what I do is request a website and response website data, but the router always on dealing.

const express = require('express')
const router = express()
const url = require('url')
const http = require('http')

router.get('/', searchHandler)

function searchHandler(req, res) {
    request('http://baidu.com', 'get')
        .then(result => {
            res.end(result)
        })
}

function request(link, method, data) {
    return new Promise((resolve, reject) => {
        link = url.parse(link)
        const result = '';
        const options = {
            hostname: link.hostname,
            port: 80,
            path: link.path,
            method: method
        }
        http.request(options, function(res) {
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                result += chunk;
            });
            res.on('end', function() {
                resolve(result)
            })
            req.on('error', function(err) {
                reject(err);
            });
        })
    })
}

module.exports = router

why does my res.end(result) not works?

Jerry
  • 91
  • 1
  • 1
  • 7
  • You probably want `res.send`, not `res.end`. – jcaron Nov 18 '17 at 00:17
  • Possible duplicate of [What is the difference between res.end() and res.send()?](https://stackoverflow.com/questions/29555290/what-is-the-difference-between-res-end-and-res-send) – Dij Nov 18 '17 at 00:18
  • Neither of those explain why `res.end(result)` doesn't also work, since it appears from the doc that it should. – jfriend00 Nov 18 '17 at 00:22
  • Do you get anything if you put `console.log()` immediately before `request()` is called or inside the `then()` block? – agm1984 Nov 18 '17 at 01:14
  • It seems that I that I don't end http request. ```javascript const http_client = http.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (chunk) { console.log(chunk) result.push(chunk); }); res.on('end', function () { resolve(result.toString()) }) }) http_client.on('error', function (err) { reject(err); }); http_client.end() ``` it works – Jerry Nov 20 '17 at 02:05

0 Answers0