Have looked for similar questions and can't find anything on this, so apologies if it already exists.
I'm pretty new to front-end work so I've got a fairly simple personal project on the go. I've got a pretty basic node/express setup and am trying to initiate a GET request to the /next-user URL
the GET is set up in the server as:
app.get('/next-user', function (req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
console.log(req.body)
})
I know a common issue with this is that the body-parser module is not setup, so here is my setup code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));
and the request is setup like;
var data = {name:"HelloServerWorld"};
console.log(data)
$.getJSON("http://localhost:8081/next-user", data, function(response){
console.log(response);
});
The server always echos an empty JSON object regardless of what I send to it where the client can see that the object is populated. I didn't want to post the entirety of the code but if it's needed then let me know, but I'm fairly confident the problem lies in what I've given so far, I'm just not sure where
GET requests don't include "req.body", req.body is used with POST requests. You may want to pass data in the form of a parameter, e.g. " "/next-user/:id" or using a POST request instead to pass over the data!
Replace console.log with res.end and you should get back the request.
Related
Basically, I am using Thunder Client to send the requests and I am using the post request. The failure that I am facing is that whenever I send the request and also send the body contents and have already used content-type application/json in the header and when at the request portion I try to get req.body it returns undefined. I don't know why this error is occurring. Could someone please help?
const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const Admin = require('../Models/Admin');
//Route 1 : Create an ADMIN Account
router.post('/createadmin', async (req, res)=>{
console.log(req.body)
res.json(req.body)
})
module.exports = router
This is a bit late so hopefully you figured it out by now, but you may need to install and then use body parser. So npm i body-parser...then you can use it as necessary demonstrated here:
I'd like to clone/relay the exact request to another URL in native NodeJs. For example, if you send a POST request to my site "example.com", it will send the exact same request you sent to another URL "example2.com" (data, headers etc). How could I achieve that?
You can use proxy middleware to duplicate the request. For example http-proxy-middleware will allow you to proxy the request to another server, but from what I can tell, you can only modify the response. Which isn't optimal if you don't want to wait on the proxy. You might just grab the main proxy library itself, something like:
const httpProxy = require('http-proxy');
const proxyMiddleware = httpProxy.createProxyMiddleware({
target: 'http://www.example2.com',
selfHandleResponse: true
});
const customProxyMiddleware = (req, res, next) => {
proxy.web(req, res);
next();
};
// This passes all incoming requests to the proxy but does not handle
// any of them. It simply passes it along.
app.use('/', customProxyMiddleware);
This code may not work exactly as intended but it should be a good starting point for what you are attempting.
I'm using the twilio API and node.js to successfully record and transcribe calls. I'm trying to implement a callback when a call is recorded. According to the twilio API, I specify my callback URL:
twiml.record({
transcribe: false,
maxLength: 30, //seconds to record
recordingStatusCallback: 'http://[url]:3000/recorded'
})
Per the documentation, I should receive some parameters back via POST, so I am logging the request and response:
app.post('/recorded', (req, res) => {
console.log(req, res)
})
What I get back in the log is a couple of giant objects, and I don't see anything that looks like the parameters I'm expecting. I'm guessing I'm supposed to be constructing that post function differently to get the parameters I need, but i'm not sure how, and I don't see any documentation in Twilio or online that shows how a successful callback function is structured.
Any ideas how to do this?
First of all add 'body-parser' module to your project.
npm install body-parser
And require it in the code:
var bodyParser = require('body-parser')
Now add it somewhere in the code before launching the server:
app.use(bodyParser.urlencoded({ extended: false })); //this will add extracting of the body for every request to express server
After that, in your functions, where you are trying to find data, you can get it using such code:
app.post('/recorded', (req, res) => {
console.log(req.body); //body of the request in javascript object format
})
Find more info about 'body-parser' module here.
I'm attempting to store an object that my user clicks on in my server so that when the page changes, all the information from that object can be displayed fully in a profile page.
I'm unfamiliar with Angular $http but I've tried to write a call that will POST to the server, unfortunately when I scan through the req object in VScode I can't find where the object I sent is contained, so I can send it on to my function.
Controller function:
$scope.storeProfile = function(child){
$http.post('/storeTempProfile', child)
.then(function(response) {
window.location.href = 'DemoPage.html';
});
}
server.js:
app.post('/storeTempProfile', function (req, res) {
profileStorage.storeProfile(req);
});
does my app.post look right? And what property of req do I need to use the dot operator on to access my object? I can't seem to find the object data anywhere in req and that makes me thing there's something wrong with how I wrote app.post
It looks like you are using express. So in that case, you want to access the object on req.body, but this will require you use body-parser. The example on their homepage:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
// create user in req.body
})
You will notice in this example that they pass the json parser into the route itself. This is only necessary if you want to have different parsers for different routes. Usually you just want to set it to all routes, which you can do by using app.use(bodyParser.json()).
I am working on a simple texteditor that saves and loads text files through an Node/ExpressJS server. Loading is fine, but saving doesn't work yet due to me not being able to transmit the data to the server-app correctly.
I send the data via XMLHttpRequest to the server in a POST request, which works fine according to the network-profiler in dev-tools, the 'handler_save' function is called, but no parameters are received.
What am I doing wrong? (here is a snippet of the server code, altered for demonstration:)
express = require('express')();
function init_save_load(){
var bodyParser = require('body-parser');
express.use(bodyParser.urlencoded({ extended: true }));
express.use('/save', handler_save );
express.use('/load', handler_load );
}
...
function handler_save(req, res){
console.log(req.body); // "{name:post.txt,data:testing}"
}
make sure you are parsing the request body so it can work
var bodyParser = require('body-parser');
app.use(bodyParser());
bodyParser is a part of "Connect", a set of middlewares for node.js. Here's the real docs and source from Connect: http://www.senchalabs.org/connect/bodyParser.html
finally console log the req.body and see what is in there
console.log(req.body)
Not only do you need to use a body parsing middleware as Abdul mentioned, but your request needs to have the correct Content-Type. Currently you are sending Content-Type: text/plain, but it should be Content-Type: application/x-www-form-urlencoded for simple forms or Content-Type: multipart/form-data for forms containing files.