3
<!doctype html>
<head>
</head>

<body>
<script>
    const Http = new XMLHttpRequest();
    const url='http://localhost:4550/users';
    Http.open("POST", url);
    Http.send("hey");

    Http.onreadystatechange = (e) => {
        console.log(Http.responseText)
    }
</script>

</body>
</html>

//user.js
var express = require('express');
var router = express.Router();

var array = [];

/* GET users listing. */
router.get('/', (req, res, next) => {
  res.send('respond with a resource1');
});

router.post('/', (req, res, next) => {
  res.send('respond with a resource2');
});

module.exports = router;

//app.js
const express = require('express')

const app = express();

app.get('/',(req,res)=> {
  console.log('lior');
  res.send('api running 2')});

app.use('/users',require('./routes/users'))

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

const PORT = process.env.PORT || 4550;

app.listen(PORT,()=> console.log('server started on port ${PORT}'));

I am new with connecting client and server side, and it might be why I couldn't find an answer for my question. Is a simple question.

As you can see I want to send "hey" from the client to the server(user.js). However I don't know how does I catch the response on the server side.

I know that a "hey" or neither the code make much sense, but is just an example to make things simple, I just wondering how does the server side could catch and handle the data.

Thanks in advance!

Isaac Michaan
  • 187
  • 10
  • The path of your router seems off. `router.post('/')` will listen to the base path. Try `router.post('/users')` instead to line up with your client – Jeffrey Devloo Dec 18 '19 at 13:56
  • @JeffreyDevloo — The base path *of the router*. Where it actually listens to depends on where it si mounted. – Quentin Dec 18 '19 at 13:57
  • 1
    sorry, I forgot the /users, but the question still remains...like how should I catch the "hey" on the server side. – Isaac Michaan Dec 18 '19 at 14:00
  • are you trying to send `hey` message to the endpoint using `POST`? It is not clear to me what you are asking. – assembler Dec 18 '19 at 14:02
  • If you do not prefix any routes with `app.use` ... (see [this](https://stackoverflow.com/questions/23923365/how-to-separate-routes-on-node-js-and-express-4), the '/' point to the socket where your server is listening on. – Jeffrey Devloo Dec 18 '19 at 14:03
  • 1
    I will add the entire code. One sec. – Isaac Michaan Dec 18 '19 at 14:03
  • 1
    Oh, trying to get the message that the client sent is done with `req.body` – Jeffrey Devloo Dec 18 '19 at 14:04
  • 1
    I think that what I was looking for, I don't know why I couldn't find in the web. anyways i tried console.log(req.body) and it didn't work. Does I need to send the "hey" in another format? – Isaac Michaan Dec 18 '19 at 14:08

2 Answers2

2

When you post data, specify how you are encoding it. It's generally best to use a standard encoding method rather than POSTing plain text. (Also don't start variable names with capital letters unless they are constructor functions)

const http = new XMLHttpRequest();
const url = 'http://localhost:4550/users';
const data = JSON.stringify({ value: "hey" });
http.open("POST", url);
http.setRequestHeader("Content-Type", "application/json");
http.send(data);

http.onreadystatechange = (e) => {
    console.log(http.responseText)
}

Then in your server side code, use a body parser to decode the data.

Since you are using an absolute URL in the request, it seems likely that you are making a cross-origin request so you also need to grant permission using CORS.

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
const port = 4550

const jsonParser = bodyParser.json()

const corsOptions = {
    origin: 'http://example.com',
    optionsSuccessStatus: 200
};

const corsMiddleware = cors(corsOptions)

app.get('/', (req, res) => res.send('Hello World!'))

app.get('/users', (req, res, next) => {
    res.send('respond with a resource1');
});

app.options("/users", corsMiddleware)

app.post('/users', corsMiddleware, jsonParser, (req, res, next) => {
    // data is in `req.body` (which will have a `value` property because the object on the client does)
    res.send('respond with a resource2');
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

(The above is untested and may have minor errors in it)

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    I am getting the following error: "SyntaxError: Unexpected token " in JSON at position 0" – Isaac Michaan Dec 18 '19 at 14:37
  • 1
    @IsaacMichaan — Looks like a bug in the JSON body parser (it seems to be following an out of date specification which doesn't let you have a JSON text consisting of just a string). Use `const data = JSON.stringify({ value: "hey" });` instead. Then you can read `req.body.value`. – Quentin Dec 18 '19 at 14:41
0

Please send serialized data as below:

const http = new XMLHttpRequest();
const url = 'http://localhost:4550/users';
const data = JSON.stringify("hey");
http.open("POST", url);
http.setRequestHeader("Content-Type", "application/json");
http.send(data);

You need to use bodyParser package

npm install body-parser

const bodyParser = require("body-parser");

and before setting up routes use it as below :

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

Don't forget to allow the headers declaration as below :

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST"
  );
  next();
});

and now you can read your data as below

router.post('/users', (req, res, next) => {
  console.log(req.body);
});
Siddharth Pal
  • 1,408
  • 11
  • 23