简体   繁体   中英

How to send data to a node.js server using client side javascript

I currently have a node.js hosted webpage that has a text box, and a submit button. Whenever you type something and click the button, the client is supposed to take whatever is inside the box, and send it to the server on a different port.

I already have a function called sendRequest() which does this whenever its clicked,

function sendRequest() {
$.get("http://***.***.***.**:8181/", {message:$("#messageBox").val()}, function(data){
    console.log(data);
});
$("#messageBox").val("");}

But my main problem is finding out how I can get a node.js server to be listening for these inputs, and export whatever is received from the client to temp.txt on the server directory

If someone could lead me to a npm package, or leave a sample of code, that would help tremendously

Edit: My server hosting looks like

var mime = require("mime"),http = require("http"),fs = require("fs");
http.createServer(function (req, resp) {
path  = unescape(__dirname + req.url)
var code = 200
if(fs.existsSync(path)) {
    if(fs.lstatSync(path).isDirectory()) {
        if(fs.existsSync(path+"index.html")) {
          path += "index.html"
        }
    }
    resp.writeHead(code, {"Content-Type": mime.lookup(path)})
    fs.readFile(path, function (e, r) {
    resp.end(r);
})}
else {
    code = 404
    resp.writeHead(code, {"Content-Type":"text/plain"});
    resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
}).listen(8080);
console.log("Listening at http://localhost:8080")

You could use axios and make a request to your specific url on an API hosted on your server. Though you might face CORS restrictions on a typical browser(client-side), if trying to reach a different domain or port.

---- Edit ---

Since Darkrum wanted me to show him how could this be solved. Even though I, have not bypassed the CORS restriction, that could be done by adding the following headers from the source server in every response.

Access-Control-Allow-Origin : *

Access-Control-Allow-Methods : GET, POST, OPTIONS

And the code to log each and every keystroke is as follows, though this is on the same server without the allow CORS.

Requirements: express, body-parser

npm i -S express body-parser

test.html

<html>
<head>
<title>test</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<input type="text" height="100" width="400" id="grabme"></input>
<script>

    $('#grabme').keypress(function(event){
        axios.post('/Mr-KeyLogger', {
            character: event.key
        }).then(function (response) {
            console.log(response);
        }).catch(function (error) {
            console.log(error);
        });
    });

</script>
</body>
</html>

Logger.js

const express = require('express')  
const util = require('util')
const fs = require('fs')
const bodyParser = require('body-parser')
const app = express()
const port = 80

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.get('/test', (request, response) => {  
  fs.readFile('test.html', 'binary', function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      var headers = {};
      headers["Content-Type"] = "text/html";
      response.writeHead(200, headers);
      response.write(file, "binary");
      response.end();
      return
  }) 
})
app.post('/Mr-KeyLogger', (request, response) => {
    fs.appendFile('temp.txt', request.body.character, function(err) {
      if (err) {
        response.writeHead(500);
        response.end();
        return
      }
      response.writeHead(200);
      response.write('gotcha');
      response.end();
      return
    })
})

app.listen(port, (err) => {  
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

You could edit the code in a way to use it with CORS as well, just replace the url in the axios post request, the CORS headers included from the source server and voila!

You show your client code but you have not really provided any details as to what your node.js server is/is doing. Is it just a static file server from the http-server package or is it an express app or something else? Normally one of these instances will only listen on one port. For example, if you setup an express app to serve your page and that application is running on port 8080 than it will also listen to CRUD requests on the same port ( GET , POST , PUT , DELETE , ...). Your client only has to send the request back to that originating port. Your server code will of course require logic to handle the request. Looking at a basic CRUD API written in express will suffice as an example here. The doc page on routing for Express shows how simple this logic can be to get started.

Without any details as to why you have to use a different port that the one which served your client, I can only guess as to the use case. So if your server is not the origin of the page containing your client code than we would need more information about the service you are interacting with:

  • Does it support CORS?
  • Does it have an API and what interchange format does it use (XML, JSON)?

From your original question, it seems to me you just want to send data back to your page's originating server (ignoring the different port requirement). That is the most common case. Otherwise,

Your server is listening to port 8000 and you're sending to port 8181 and you expect the server to listen? That's illogical.

Anyway, you can do a trick: Let the requests which come at port 8181 to be forwarded to 8000. This link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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