简体   繁体   English

使用纯NodeJ放置请求

[英]Put Request using pure NodeJs

I am new to nodejs. 我是nodejs的新手。 I am trying a basic example using http requests Get,Post and Put. 我正在尝试使用http请求Get,Post和Put的基本示例。 I am done with POST and GET. 我已经完成了POST和GET。

var http = require("http");
var port = 8081;

function getLogin(req, resp){
    resp.writeHead(200, {"Content-Type" : "text/html" });
    resp.write("<html><body><form action='http://localhost:8081/home' method='post'><table><tr><td>Username : <input type='text' name='username' id='username' required/></td></tr><tr><td>Password  : <input type='password' name='password' id='password' required/></td></tr><tr><td><input type='submit' value='Login' /></td></tr></table></form></body></html>");
resp.end();
}

function getHome(req, resp){
     resp.writeHead(200 , {'Content-Type':'text/html'});
     resp.write("<html><body>Niranth<br><input type='button' value='Add Skill'/></body></html>");
     resp.end();
}

function getSkill(req, resp){

}

function get404(req, resp){
    resp.writeHead(404, "404", {"Content-Type" : "text/html" });
    resp.write("<html><body>404</body></html>");
    resp.end();
}


http.createServer(function(req, resp){
    if(req.method == 'GET'){
        if(req.url === "/"){
            console.log("hello get");
            getLogin(req, resp);
        }
        else
            get404(req, resp);
    }
    else if(req.method == 'POST'){  
        var data = '';
        if(req.url === "/home"){
            req.on('data', function(chunk) {
              data += chunk;
              console.log("hello post");
            });

            req.on('end', function() {
              // parse the data
              getHome(req, resp)
            });
        }
        else{
            console.log("error");
        }
    }    
    else if(req.method == 'PUT'){
         getSkill(req, resp);
    }

}).listen(port);

All I need is a PUT request on 'ADD SKILL' button in my response. 我只需要在响应中的“添加技能”按钮上输入PUT请求即可。 I am not using 'Request' or 'Express' modules. 我没有使用“请求”或“表达”模块。 Any suggestions how to go forward with PUT request ? 有什么建议如何进行PUT请求吗?

May be this helps: 可能会有所帮助:

 var postData = {name:'someName'}; var options = { hostname: '<HOST_NAME>', // www.examplehost.com port: 80, path: '<PATH>', // /upload_something method: 'PUT', headers: { 'Content-Type': '<CONTENT_TYPE>', // application/x-www-form-urlencoded 'Content-Length': postData.length } }; var req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.') }) }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM