0

I want to send form data to web-server by using Node.js, So I use "request" module that is very famous in nodeland. And It's cool, There is no problem, But because of some reason (write-stream encoding non-supported), I have to change it to built-in module, "http".

I think beneath codes are same to post some data to web-server, When I using "request" module, There is no problem so can get 200 response, success to sending data.

But in "http" module, I got a 302 response that redirects to another page. and failed post data. I don't know what is problem with, maybe it is something URL trouble, http use 'host and path' on the other hand, request use 'url' . I don't know how can I solve this, I stucked 2 days, please let me know If you have some hints..

Thanks.

By Using "Request" Module

function postFormByRequestModule() {

   request({
        url: 'http://finance.naver.com/item/board_act.nhn',
        headers: { 'Content-Type': 'text/plain' },
        method: 'POST',
        form: {
            code:'000215',
            mode: 'write',
            title: 'This is Title',
            body:'This is body'
        }
    }, function (error, response, body) {
        if (error) {
            console.log(error);
        } else {
            console.log(response.statusCode, response.body);
        }
    });
}

By Using "Http" Module

var postData = querystring.stringify({
            code:'000215',
            mode: 'write',
            title: 'This is Title',
            body:'This is body'
});


var options = {
    host: 'finance.naver.com',
    path: '/item/board_act.nhn',
    method: 'POST',
    headers: { 'Content-Type': 'text/plain', }
};

var req = http.request(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
    res.on('end', function() {
        console.log('No more data in response.')
    })
});

req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

function postFormByBuiltInHttpModule() {
    req.write(postData);
    req.end();
}

1 Answer 1

0

The built-in http client does not automatically follow forwards, whereas the request module does (and has many other "high level" features). So if you want to continue using the built-in client, you will need to manually check res.headers.location and retry the request at that url.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.