Thursday 8 June 2017

Node.js and ExpressJS body-parser package retrieve data

OK first time user of Node, and I am trying to send data to backend/index.js

Requirements

  • Post data to back-end node
  • Retrieve posted data and store values as variables

Whats the problem

The post is 200 success, that works.

however when I navigate to :

http://localhost:8080/backend/index

I get :

Cannot GET /backend/index

Where am I going wrong ?

Here is my front end post post

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8080/backend/index.js",
  "method": "POST",
  "headers": {
    "content-type": "application/x-www-form-urlencoded"
  },
  "data": {
    "id": "1223",
    "token": "223",
    "geo": "ee"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

I am trying to retrieve this data from and store as variable in the back end node.

backend/index.js

// grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// routes will go here

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// POST http://localhost:8080/api/users
// parameters sent with
app.post('/backend/index', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});



via Beep

No comments:

Post a Comment