Express POST response-object not being updated when request parameter is changed - json

I am trying to make a tool to view our projects configuration JSON file. The config is generated based on what process.env variables are set. I've created an express server with one route that listens for the environment variables and returns the corresponding JSON configuration. However this only works on the first request, the correct process.env variables are being changed, but the JSON config being returned only reflects the first request made. Below is the POST route - the fpconf object should change to reflect the request parameters being sent. Is there some something I'm missing?
app.post( '/json', function ( req, res, next ) {
res.header( "Access-Control-Allow-Origin", "*" );
res.header( "Access-Control-Allow-Headers", "Origin, X-Requested- With, Content-Type, Accept" );
console.log( req.body );
_.merge( process.env, req.body );// Sets environment variables grabbed from post request
console.log( process.env ); // Log to ensure environment variables have been changed.
var fpUtils = appRootPath.require( '/libs/helpers/fputils' ),
fpconf = appRootPath.require( '/libs/fp-conf' );///file that returns the configuration JSON
console.log( "instance is " + process.env.NODE_APP_INSTANCE + ", deployment is " + process.env.NODE_ENV )
console.log(fpconf.data);
res.send( fpconf.data );
});

Related

Send a post request on PostMan

I have the following method I want to test using PostMan
public returnType name( String var1, String var2,String var3, String var4);
I tried to send a post request to test I sent one like this but it does not work:
{
"var1": "GU4777",
"var2" : "HU 888",
"var3" : "NU 8890",
"var4" : "UJ 9909"
}
I get this error:
I get this error: 10:11:16.588 [http-nio-8080-exec-3] WARN org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper - javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
Can you guys please tell me the exact syntax I can use?
Thank you in advance;
Rest API
In order to do what you want to do you first need a HTTP server that listens for requests on a certain endpoint let's call that endpoint /test.
The server then must parse the JSON request body when it receives the request, extract the parameters and can then call the method name() using those parameters.
Here an implementation of a server like this using JavaScript and express.js. You do not need a library for a simple server like that (but I have used one here by reason of simplicity) and you can implement the server in pretty much any language you like e.g. Java.
While the syntax will differ in another language the idea will be the same.
import express from "express";
// create app
var app = express();
// middleware to parse json
app.use(express.json())
// listen for requests on the /test endpoint which you will hit with Postman
app.post("/test", function (req, res) {
// extract variables from json body
const var1 = req.body.var1;
const var2 = req.body.var2;
const var3 = req.body.var3;
const var4 = req.body.var4;
// call method
name(var1, var2, var3, var4);
// send response with HTTP code 200
res.status(200).send({
"message": `Executed name() with var1 = ${var1}, var2 = ${var2}, var3 = ${var3}, var4 = ${var4}`
});
});
// the function that you want to call on the server
function name(var1, var2, var3, var4){
console.log(var1, var2, var3, var4);
}
// start HTTP server and listen for requests on port 3000
const port = 3000;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
You then need to start your server. In this case you do that by executing node server.js and then you can send requests to the server using Postman.
First, put your JSON payload (= the JSON from your question) into the request body and hit the localhost:3000/test route with a POST request. You should then receive a response with status code 200.
On the server side you can observe this:
RPC/ gRPC
In order to "directly" invoke a function on a server you might wanna have a look at RPC or gRPC for your preferred language.
I decided to use request path wish solved the issue.

Unable to access data inside a string (i.e. [ object Object ]) that was originally sent as a JSON object

I'm using axios to send a JSON object as a parameter to my api. Before it post request is fired, my data starts of as a JSON object. On the server side, when I console.log(req.params) the data is returned as such
[object Object]
When I used typeof, it returned a string. So then I went to use JSON.parse(). However, when I used that, it returned an error as such
SyntaxError: Unexpected token o in JSON at position 1
I looked for solutions, but nothing I tried seemed to work. Now I'm thinking I'm sending the data to the server incorrectly.
Here's my post request using axios:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/${mediaData}`)
return json;
}
Any thoughts on how I can solve this?
You need to update your code using axios to provide the mediaData in the body of the request instead of the URL:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/`, mediaData)
return json;
}
In the backend (assuming you're using express here), you need to configure your application to use bodyParser:
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
And then in your controller update your console.log(req.params) to console.log(req.body); then restart your node server

Server not returning JSON from Express to React (proxy)

I'm attempting to make an application that has a React frontend (running on port 8080) and an Express-Node.js backend (on port 3000). I'd like for my client to use fetch to request data from my server. So far, what I've read online indicates that I need to add a proxy entry to my package.json with the value of http://localhost:3000. I've done this, my server receives the request correctly, but its response is not what I expect (a JSON object). What am I doing wrong?
//Server
app.get('/search', function(req, res) {
...
//console.log(section) <-- Is the correct value
res.json(section);
})
...
app.listen(3000)
//Client
handleTouchTap() {
fetch('/search?crn=10001').then(function(response) { //<-- Hard-coded for testing
return response; //<-- Does not contain the value of "section" from server
}).then(function(data) {
console.log(data); //<-- Likewise, does not contain the value
});
}
//From package.json
...
"proxy": "http://localhost:3000",
...
You need to pull the json out of your response:
fetch('/search?crn=10001')
.then(response => response.json())
.then(section => console.log(section));

Accessing req.body values in express

I'm working on a REST API node/express app. For my 'signup' route, where a user uses the api to sign up for the service, it takes a POST'ed JSON object. Inside this function I want to check against the mongo db to make sure that this user doesn't already exist.
The problem is I need to get the username from the posted json information, but every attempt I have made has failed. The lines that attempt to log the req.body.username and req.body.password always return 'undefined'. What am I doing wrong?
Here's the code I have so far is below:
exports.signup = function(req, res) {
// todo: somehow verify that username, password, email and phone number are all provided.
// do not write into the collection unless we know all the information has been provided.
// maybe access the JSON elements to make sure they are not null
// todo: also make sure a record doesn't already exist for this uer
var user = req.body;
// need to get the username here somehow
var JSONuser = JSON.stringify(user);
// console.log('user: ' + user);
console.log('userJSON: ' + JSON.stringify(user));
console.log('username: ' + req.body.username);
console.log('password: ' + req.body.password);
db.collection('users', function(err, collection){
//if ( collection.findOne({}) ) { // make sure the user doesn't already exist here
collection.insert(user, {safe:true}, function(err, result){
if(err){
res.send({'error':'An error has occured'});
} else {
console.log('Success: ' + JSON.stringify(result[0]));
res.send(result[0]);
}
})
//}
});
}
By default in express, you don't have access to those variables through dot syntax. You would have to parse the response. Luckily, we have a package for that.
Use body-parser middle ware for easy access to post variables.
// install it
bash$: npm install body-parser
// require it in your project
bodyParser = require('body-parser');
// `use` it in your express app
app.use(bodyParser.urlencoded({ extended: true}));
// now you your post values are available on the req.body.postVariableName
I use this in almost all of my projects, it just makes it easy.
* EDIT *
I looked at your repo and everything actually looks fine as it pertains the reading of parsed values; however, they way you are console logging them may be where you are getting confused. I rewrote your signin route so I could explain better.
exports.signin = function(req, res) {
var user = req.body;
console.log('req.body: ' + JSON.stringify(user));
console.log('Signing In As User: ' + user.username);
console.log('Password: ' + user.password);
res.send('You just signed in!');
}
I tested this my opening up another terminal and curling a JSON post.
curl -H "Content-Type: application/json" -X POST -d '{"username":"testuser","password":"testpassword"}' http://localhost:3000/signin
As you can see it should work.
Some things worth mentioning. When you wrote console.log('req.body: ' + req.body);. You are not going to see the data you want. You are going to see req.body: [object] in the output because javascript is going to render this as req.body.toString() which is just the identifier. If you want to post the code, use JSON.stringify(req.body) or use console.dir(req.body).
Second, req.body will just give u access the body object.
// this is just user.toString() which is again [object]
console.log('Signing In As User: ' + user);
// You need to use the dot syntax to get user.username
console.log('Signing In As: " + user.username);
If you are stilling seeing issues, its because of the way you are making posts localhost, not because of your code.

mocha - send json to post express route

I'm trying to send some json data to my '/sign_up' route in mocha test.
request = require 'supertest'
express = require 'express'
app = express()
Authentication = require("#{specDir}/../apps/authentication/routes")
authenticate = new Authentication app
Factory = require "#{specDir}/factories/user"
user = Factory.build 'user'
it 'creates an account', (done) ->
request(app).post('/sign_up').set('Accept', 'application/json').send(user).end (err, res) ->
expect(res.statusCode).to.equal 200
done()
However req.body in the callback function is undefined. Below I've shown a snippet of my route callback
#app.post '/sign_up', (req, res) ->
res.format
html: -> res.status(406).send 'invalid Content-Type'
json: ->
console.log req.body
res.status(200).send status: 'ok'
Probably I'm missing some small detail, but can't see what.. any ideas?
P.S. I'm well aware of that the tests pass and it does what it should, but before I move on to write more tests I gotta know how to send some data.
You're missing a body parser, add app.use(express.json()) in your code somewhere.