Lost HTTP request body - javascript

I am using Groovy script to perform HTTP POST request with some data:
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
def http = new HTTPBuilder('myhost.com')
http.request( POST ) {
uri.path = '/'
requestContentType = ContentType.JSON
body = [title: 'some data', desc: 'some more data']
log.info(body.title)
response.success = { resp,reader ->
log.info( "POST response status: "+resp.statusLine+"}")
}
}
This works just fine, Groovy results are below:
Logs:
INFO : some data
INFO : POST response status: HTTP/1.1 200 OK}
But when I see my web service logs the request body is undefined:
Here's the code:
const express = require('express');
const app = express();
var test = {0:'post'};
app.get('/', (req, res) => {
res.send('a');
console.log('request inbound');
});
app.post('/',(req,res) => {
res.send('test');
console.log('post in');
console.log(req.body);
});
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 30000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
I'm using Node.js v12.13 | npm v6.12 | express.js 4.17.1

I'm afraid you've omitted app.use(express.json()).
const express = require('express');
const app = express();
app.use(express.json())
var test = {0:'post'};
app.get('/', (req, res) => {
res.send('a');
console.log('request inbound');
});
...

Related

Curl is allowing POST requests but browser is not

I am trying to develop an API that allow POST request of file data, but the POST request only functions using curl curl -X POST --data file= mouse.fa "http://localhost:3000/api/data?file=mouse.fa" . When I trying a POST request in the browser, I get a GET error Cannot GET /api/data. Please could you advise me on how to get the POST request to work in the browser in addition to curl.
router.js
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
fileParser = require("./fileParser")
router.use('./fileParser', fileParser.parse);
// middleware
router.use(function (req, res, next) {
console.log('Received request');
next();
});
router.post('/data', function (req, res) {
//Check file is valid
if (!req.body.file.toString().endsWith('.fa')) {
res.status(400).json({ message: "Bad Request" });
} else {
fileParser.parse(`./${req.body.file.toString()}`);
res.json({ message: "File parsed and data submitted.", location: "/data/" });
}
});
server.js
const express = require('express');
// create server
const app = express();
const port = 3000;
app.listen(port, function () {
console.log(`Server running at ${port}`)
});
// import router
const router = require('./router');
app.use('/api', router)

supertest not found error testing express endpoint

I tried to set up jest, supertest, and express but failed. I have these 2 simple file
index.js
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => res.send("Hello World!"));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
and index.test.js
const express = require("express");
const app = express();
const request = require("supertest");
describe("/", () => {
test("it says hello world", done => {
request(app)
.get("/")
.expect(200)
.end(function(err, res) {
console.log("err", err);
});
});
});
when I run the test I'm getting this error.
err Error: expected 200 "OK", got 404 "Not Found"
What's wrong?
I visit localhost:3000 in my browser I can see 'Hello World!'
you should refactor index.js and create app.js
app.js
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Hello World!"));
index.js
const app = require('./app')
const port = process.env.PORT
app.listen(port, () => { console.log(`listening on ${port}) . })
the reason why we restructure the code like this is we need to access to express app() but we do not want "listen" to be called.
in your test file
const request = require("supertest");
const app = require("../src/app");
describe("/", () => {
test("it says hello world", done => {
request(app)
.get("/")
.expect(200)
.end(function(err, res) {
console.log("err", err);
});
});
});
It's because app instance in your test is different from the one running in your index.js
Export app from your index.js:
const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`));
module.exports = server;
And import in your test:
const server = require('./index.js');
// pass your server to test
...
request(server)
.get("/")
...

How to facade (proxy) websocket port

I have server side rendering react app in which i have proxied all http calls to different port. Please see the code below for http proxy.
import proxy from "express-http-proxy";
const app = express();
const bodyParser = require("body-parser");
const http = require('http');
const httpProxy = require('http-proxy');
const PORT = process.env.PORT || 3001;
httpProxy.createServer({
target: 'ws://localhost:4000',
ws: true
}).listen(PORT); //Throws error since 3000 port is already used by //app.listen.
app.use(
"/api",
proxy("http://localhost:4000/", {
proxyReqOptDecorator(opts) {
opts.headers["x-forwarded-host"] = "http://localhost:4000/";
return opts;
}
})
);
app.post("/logger", (req, res) => {
logger.debug(req.body.data);
res.send({ status: "SUCCESS" });
});
app.listen(PORT, () => {
logger.debug(`Portal listening on ${PORT}`);
});
that means when i make any calls /api/endpoint it will redirect to localhost:4000/endpoint but will be seen in the network as http://localhost:3000/endpoint1
I want the same behaviour with websockets as well.
I am using new WebSocket(ws://localhost:3000/endpoint1); It should redirect to ws://localhost:4000/endpoint1.
and should be shown in network tab as ws://localhost:3000/endpoint1
Resolved it by using another library http-proxy-middleware
import httpproxy from "http-proxy-middleware";
import proxy from "express-http-proxy";
const app = express();
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3001;
const wsProxy = httpproxy('/ws', {
target: 'ws://localhost:4000',
pathRewrite: {
'^/ws' : '/', // rewrite path.
'^/removepath' : '' // remove path.
},
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
ws: true, // enable websocket proxy
logLevel: 'debug'
});
app.use(wsProxy);
app.use(
"/api",
proxy("http://localhost:4000/", {
proxyReqOptDecorator(opts) {
opts.headers["x-forwarded-host"] = "http://localhost:4000/";
return opts;
}
})
);
app.post("/logger", (req, res) => {
logger.debug(req.body.data);
res.send({ status: "SUCCESS" });
});
app.listen(PORT, () => {
logger.debug(`Portal listening on ${PORT}`);
});

Error setting cookie and getting a json response with router.post in express, node.js

I'm trying to set a cookie with a post method in order to do some db query and put it back in the cookie value, as well as returning a json with the user data.
It works, the cookie is set and I get the json on http://localhost:8080
but I get a message from the compiler:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How can I fix it so it won’t make this error?
my file structure is:
root/ app.js
root/controllers/ cookie.controller.js
root/routes/ cookie.route.js
app.js
const express = require('express');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || process.argv[2] || 8080;
app.use(cookieParser());
app.use(require('./routes/cookies'));
app.use(cors());
app.listen(port, () => console.log('cookie-parser demo is up on port: ' + port));
cookie.route.js
const express = require('express');
const cookieController = require('../controllers/cookies');
const router = express.Router();
router.use(require('cookie-parser')());
router.post('/', router.use(cookieController.getCookie));
module.exports = router;
cookie.controller.js
exports.getCookie = (req, res, next) => {
let auth = req.cookies.auth;
//...db queries, get userData
let userData = {
id: '123',
token: 'sfsdfs34',
email: 'user#gmail.com'
};
// if cookie doesn't exist, create it
if (!auth) {
res.status(200)
.cookie('auth', userData.id)
.json({ message: 'it works!', user: userData });
req.cookies.auth = userData.id;
}
next();
};
You're modifying the request cookie headers after sending the response at the end of your getCookie controller. You should remove req.cookies.auth = userData.id, and use res.cookie() instead before sending the response.
const express = require('express')
const cookieParser = require('cookie-parser')
const app = express()
app.use(cookieParser())
app.get('/', (req, res) => {
if (!req.cookies.auth) {
res.cookie('auth', { id: '123' })
}
res.json({ message: 'It worked!' })
})
app.listen(8080, () => console.log('http://localhost:8080))
Problem was solved after deleting the cors from app.js

index.js cannot get / when accessing localhost:5000

const FatSecret = require('./fatsecret');
const fatAPI = new FatSecret('50cee42503b74b4693e3dc6fccff8725','2755697297a84ac5a702461b166e71f6');
// Express webhook
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000
app.use( express.json() );
app.post('/', (req, res) => processWebhook( req, res ));
app.listen(PORT, () => console.log(`Listening on port ${ PORT }`));
var processWebhook = function( request, response ){
if (request.body.result) {
processV1Request(request, response);
} else if (request.body.queryResult) {
processV2Request(request, response);
} else {
console.log('Invalid Request');
return response.status(400).end('Invalid Webhook Request (expecting v1 or v2 webhook request)');
}
}
I'm trying to access localhost:5000 but I get error cannot get /
I'm using API from here
Dude, if what you say is true, you are trying to GET that endpoint, but your route is a POST:
app.post('/', (req, res) => processWebhook( req, res ));
Try:
app.get('/', (req, res) => processWebhook( req, res ));
Nevertheless I think you really do want to POST (since you need a body). If you are testing your app as it stands, make sure you are POSTing!

Categories

Resources