G
G
Galdar Turin2020-09-03 09:40:52
Node.js
Galdar Turin, 2020-09-03 09:40:52

How to create a server for accepting POST GET requests?

Good afternoon.
I want to create a server to receive GET POST requests. I found an interesting article ( https://webdevblog.ru/chto-takoe-cors/ ). But I want to create two classes.
1) This is the server itself that receives requests
2) This is just a file that will send data to the same server on a given port GET POST

If I answered the 1st question. How to send data from your server to your socket GET POST requests.
Here is a GET request

GET
request({
    method: 'GET',
    url: 'http://ХХХХХХ:4554/private',
    // параметры GET-запроса
    // index.php?param=edit&value=10
    qs: {
        param: 'edit',
        value: 100
    }
    }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
        // валидация и 
        // обработка полученного ответа, заголовков
        GET = body;
    }
})


But I can't generate POST. I find an example, but it sends an empty body
POST
var POST = '';

request.post({
    url: 'http://ХХХХХХ:4554/login',
    headers: { 'Content-Type': 'application/json' },
    body: {
        login: 'login1',
        password: 'password1'
    }
    }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
        // валидация и 
        // обработка полученного ответа, заголовков
        POST = body;
    }
})


This is what a GET POST request socket looks like
socket
/**
 * Подключение модулей и конфигураций
 */
// Файл конфигураций
const manifest      = require("./manifest.json")
// API HTTP
const express       = require('express')
// Session
const session       = require('express-session')
// HTTP
const { request }   = require('http')

const ALLOWED_ORIGINS = [
    'http://ХХХХХ:4554',
    'http://ХХХХ:4554'
]

/**
 * Объявление модулей и конфигураций
 */
// API HTTP
const app           = express()
// Порт соединения
const PORT = manifest.connection.PORT

const sessionOptions = {
    secret: '123456',
    cookie: {
      maxAge:269999999999
    },
    saveUninitialized: true,
    resave:true
};

app.use(session(sessionOptions));

app.options('*', (req, res) => {
    res.set('Access-Control-Allow-Origin', '*');
    res.set("Access-Control-Allow-Headers", "Content-Type");
    res.send('ok');
});

// GET
app.get('/public', function(req, res) {
    console.log(res)
    console.log(req)
    res.set('Access-Control-Allow-Origin', '*')
    res.set('Access-Control-Allow-Credentials', 'true')
    res.set('Access-Control-Allow-Methods', 'GET, OPTIONS')
    res.set('Access-Control-Allow-Headers', 'Content-Type')
    res.send(JSON.stringify({
        message: 'This is public info'
    }))
})

// POST
app.post('/login', function(req, res) {

    console.log('POST')
    console.log(req.body)

    if(req.body.password === 'secret') {
        req.session.loggedIn = true
        res.send('You are now logged in!')
    } else {
        res.send('Wrong password.')
    }

})

app.get('/private', function(req, res) {

    //console.log(req)
    //console.log(res)

    //console.log(req.headers)
    //console.log(ALLOWED_ORIGINS.indexOf(req.headers.origin))

    if(ALLOWED_ORIGINS.indexOf(req.headers.host) > -1)
    {
      res.set('Access-Control-Allow-Credentials', 'true')
      res.set('Access-Control-Allow-Origin', req.headers.origin)
    }
    else
    { // разрешить другим источникам отправлять неподтвержденные запросы CORS
      res.set('Access-Control-Allow-Origin', '*')        
    }

    // let caches know that the response depends on the origin
    res.set('Vary', 'Origin');

    if(req.session.loggedIn === true)
    {
      res.send('THIS IS THE SECRET')
    }
    else
    {
      res.send('Please login first')
    }

})

app.listen(PORT, (err) => {
    if (err) {
        return console.log('something bad happened', err)
    }
    console.log(`Server is listening on ${PORT}`)
})


And as I understand it, Access-Control-Allow-****** headers can be omitted? If requests will arrive from server to server.

Maybe someone has already done something similar and can give valuable advice on how to do it better.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question