So I've been working on this React/Node application since August now. Never encountered such issue. Been trying to fix, but it just wouldn't happen.
So React is sending an Axios request to Express, and in the first middleware Tier req.body is empty. I tried to change headers back and forth. So changing them to urlencoded actually turns the req.body into this {'entire stringified payload':''} so as if it's an object with a stringified JSON payload as the property name. Setting the headers as application/json doesn't do anything.
(async function(x) {
await Axios.post(`https://${x}/dispositionController/executeDisposition`,payload)
})(this.props.correctEndpoint)
This is the piece of code that is sending data to Express. I didn't want to make it an IIFE, I tried many things, and made it an IIFE out of desperation. This is middleware tier in Express where req.body is empty it is actuall the first middleware tier after error-handling middleware tier for http.
dispositionController.use((req,res,next)=>{
console.trace(req.body,'req.body here');
console.trace(req.body.Note,'req.body.Note');
throw new Error('');
global.thisSocket.to(`${req.body.dispoSocketID}`).emit('postingDispo');
req.body.Note=req.body.Note.replace(/[^A-Za-z]/g,"");
switch(req.body.eventID) {
case 5:
req.body.typeOfRegular='Inbound';
break;
case !5:
req.body.typeOfRegular='Outbound';
break;
}
next();
})
Please help.
Related
I am using http-proxy-middleware to create a proxy and it's running successfully.
Before calling app.use('/',proxy_options);
I am trying to intercept my request and modifying the request header but updated value is not reflecting in headers.
app.use('/',(req,res,next)=>{
const token=getToken();
req.header['authorization']=token;
next();
});
Even I tried with req.header.authorization=token; and also without next();.
When I am trying to print the my request header authorization:'' is coming as blank.
Can any one let me know why this happening and how I can resolve this.
Any help or suggestions must be appreciated.
If your getToken() function is fetching token from other apis, then you should add await in front of it.
Try to use below code,
app.use('/', async (req,res,next)=>{
const token=await getToken();
req.headers['authorization']=token;
next();
});
You also need to replace header by headers, as mentioned above in code snippet.
It should work.
I want to update a document in Mongo, but when I send an Axios POST request to the server with params for the updates I receive nothing but a blank object on the server side - I'm using Node.js with an Express server (MERN stack).
I have tried the qs library module and Node's querystring module. I tried including headers with
'Content-Type': 'application/x-www-form-urlencoded' and 'application/json'.
My Axios POST request:
const A = 1;
const B = 2;
const data = { A, B };
console.log(qs.stringify(data)); // A=1&B=2
axios.post(url('upVote'), qs.stringify(data));
The server route:
app.post('/upVote', async (req, res) => {
console.log(req.params); // {}
await DB.updateVote(ID, collection, voteCount);
res.end();
});
The headers as shown by Chrome's DevTools.
... Also, all my axios.get() requests work fine and grab data from Mongo and send it back to my app properly, and the url/endpoints match.
There are a couple of ways to send data to the server with axios.
I see the confusion with the documentation in axios, I have not seen this usage before and it does seem to be broken upon looking at the request logs and object.
1) axios.post receives body of the request as a second parameter. So if you want to pass parameters to axios, you should do something like this:
const B = 2;
const data = { A: 1, B: 1 };
axios.post(url('upVote'), {}, { params: data });
Note that axios will handle stringification on it's own and that the third parameter is a config object.
On the server the params will be available at request.query
2) If you want to stringify the parameters yourself, then you should append them into your URL like so
axios.post(`url('upVote')?${qs.stringify(data)}`);
Same here, data on the server will be under request.query
3) It's generally better to use the body of the post request to transfer large data payloads for convenience. You should also consider what your caching strategies are and if they rely on request url without the consideration of request body it may be a concern.
axios.post(url('upVote'), data);
In this case data on the server will be under request.body
UPD: Originally forgot to mention that you will need a body-parser middleware to access request.body.
4) You can use axios without method shorthands which may be useful for some people
axios({
method: 'POST',
url: url('upVote'),
params: data
})
This is identical to the example in 1.
And all of them return a Promise which you can .then().catch() or await.
I think you want .body instead of .params.As you are sending data in body by post using axios. You are printing params which will print nothing for this url/api .
Try
console.log(req.body) // instead of req.params
If this did not work then please show us your react code.
Moreover
In react you have to add .then() after axios else it will say unhanded promise
To get params on server side you have to make some changes
In axios (react)
axios.post(url('upVote/param'), qs.stringify(data));
In server
app.post('/upVote/:params', async (req, res) => {
console.log(req.params)
.....
})
I think you are calling res.end(). I think it should be res.send(...)
This answer should help: https://stackoverflow.com/a/29555444/1971378
I'm currently getting started with Sails.js, and I want to add user accounts to my toy app, so I installed the "sails-auth" package that creates a Passport-based user authentication system. I can create new users by sending POST /user, and I can sign in with POST /auth/local.
The documentation says:
Authenticate with the local strategy via a POST to /auth/local with params identifier (email) and password). This will also create a session. See passport.local for more.
However, when I try to GET /user/me, which routes to a controller action that should return the current user in the session, the page instead gives an empty response. Why is this happening? Is there some kind of configuration step that I'm missing?
By the way, I haven't changed or messed around with the sails-auth package. It's still completely new; the "me" action looks like this:
me: function (req, res) {
res.ok(req.user);
}
EDIT: I've found a temporary workaround by searching the issues in the sails-auth repo. Instead of getting a user object from req.user, you can get a string user ID from req.session.passport.user.
Your me action as written is only going to return whatever you are passing in as the user param. Sails builds on top of Express.js so req is the request from the browser and res is the response to the browser.
Most likely you are sending the data to your me action in the req body which is why your response is blank, simply put, req.user is empty so the response is empty. In that case you would access it with req.body.user, you could also try var user = req.params();
For debugging and just generally getting a feel for how the req and res objects are structured I suggest you always start sails (in development, never in production) with the verbose flag.
sails lift --verbose
Then you can do this:
me: function(req, res){
sails.log.verbose(req);
res.ok(req.user);
}
And have it print out the entire req object so you know what's in req.user.
Typically though you would do a database lookup as the user param would be an id. Which means your me function might look (something, obviously depending on your dbc it might be pretty different) like:
me: function(req, res){
var userId = req.body.user;
User.find({'user_id': userId}.exec(function(err, user){
if(err){
//tell peeps there was an error
}else{
res.ok(user);
}
});
}
Best debugging for routes and for the request object:
'/*' : function(req, res, next) {
sails.log.verbose("method: ", req.method, "\n body: ", req.body, "\n url:", req.url);
next();
},
Just paste that at the start of your routes module.
I am trying to write a json object in my node application, integrating the Twilio API. When console logging the object all objects are returned properly but when I write it to the document only the first object is written. Why? How should I change the code to see the same written response as in my console log.
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.get('/', function(req, res) {
var accountSid = 'xxx';
var authToken = 'xxx';
var client = require('twilio')(accountSid, authToken);
client.messages.list({
from: "xxx",
to: "xxx"
}, function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body); // THIS WILL DISPLAY ALL OBJECTS
res.json(message.body); // THIS WILL ONLY DISPLAY THE FIRST OBJECT
});
});
});
app.listen(1337);
I am new to Node JS and think this is easy to solve, but I still can’t find the solution.
res.json(...); sends back the response. You are doing that in the first iteration over the array, hence the client only gets the first message.
If you want to extract body from all messages and send all of them back, then do that. Create an array with the data you want and send it back. Example:
res.json(data.messages.map(function(message) {
return message.body;
}));
You can only call res.json once per request. You're calling it multiple times in a loop. The first time you call it, the browser receives the response, and you'll get a headers already sent exceptions (or something like that) for all other res.json calls.
res.json actually does a data conversion to JSON. I'd be willing to bet there is something it is not dealing with, or it's simply screwing it up. If the response from Twilio is already json, you probably don't need to do that. Try res.send, instead, which just returns whatever you got back.
So I have a route in my Express app with two middleware in them:
app.foo('/thisRoute', fancyMiddleware.one, fancyMiddleware.two);
Both middlwares function in order just fine. However, in fancyMiddleware.one I have this:
var one = function(req, res, next) {
...
...
res.cookie('myCookie', data, {maxAge: 3600000});
console.log(req.cookies.myCookie)
return next();
}
To test everything I'm using PostMan to test all my requests.
The logged output for req.cookies.myCookie always returns undefined. But in the Body tab I can see that the cookie is present.
If I log out the same cookie in fancyMiddleware.two its also undefined.
why is this returning undefined?
EDIT: So, with a few answers of "why" being given, I now realize I should have also asked:
How do I read the cookie I just set?
I dont really need it right after I set it in fancyMiddleware.one, but I do need it in fancyMiddleware.two
EDIT 2: I forgot to mention I'm working with an Express 3 setup. Probably relevant.
The req.cookies is populated only once, when the cookie parser middleware is executed.
res.cookie() immediately sets the Set-Cookie header, so you'll have to use res.get('Set-Cookie') to see the current values.
You are setting the cookie on the response-object res, but you are asking it from the request req.