express.json() block request reach latter middleware - json

When my program like this, the former middware can send string 'Hello world' to Postman.
app.use((req, res, next) => {
console.log(req.body);
res.send('Hello world');
next();
})
app.use(express.json());
})
But I don't know why when I put the test middleware after app.use(express.json()), it do not send anything. I use postman to send post request with raw data of type json.

You must declare that middleware express.json before than any route handlers, because that middleware is in charge of parsing the information of the request and put into the request body property, after that it automatically call next to continue the execution flow. If you put that middleware at the end of your request, after the parsing of the information next will be called as you don't have more middleware to manage the execution flow your server hangs.

OK, I just found that because my POSTMAN POST request use raw json with single quoted instead of double quoted. I changed it into double quoted so it worked. Thanks.

Related

How can I send data (string) from my html to my server (node or express) and execute certain function with it?

I have a node.js server running and is executing what I want it to do, create an excel document with data fetched with Axios from an API, now, I want to allow a user to input a string on my HTML and then send that string to my web server, and perform an Axios request to the API that I am consuming. How can I do that? Should I use a POST request, a PUT request, or anything else?
Thanks!
You should be able to send data from your client to the server via the request body regardless of the request method whether GET/POST/PUT.
fetch call would look like this
// just a simple get request
fetch('/example-endpoint', {
method: 'POST',
body: {
data: 'String to be sent'
}
});
And on your node express server
app.post('/example-endpoint', (req, res) => {
const data = req.body.data;
// do stuff with your data here.
})
GET request method is used for getting data, while POST and PUT are used for creating and updating data, so use them as you need them.
POST request to your server, like uh https://myserver.com/api/${userString}
something like that

How to authenticate a user in es6 while data coming from API?

I have an API which is working fine on Postman and getting a result when I provided the email and password in the header section ,now I have a login form and I want to authenticate the user from that API data result if the user name and password matched with API data then logged in otherwise show error. This type of work I wanted but I am very confused where to start it.and I only want to use es6 functions.
You create a login function that makes an ajax call to your API, probably using the fetch API (or some other ajax library like Axios). Your call returns a promise, with the result from the server, which you then act upon.
const login = (formValues) => {
return fetch('/your/api/url', {
method: 'POST',
body: JSON.stringify(formValues)
})
.then((response) => JSON.parse(response))
.then((data) => {
// do something with the server data
})
.catch((error) => {
// do something with the error
});
};
That's the gist. Your server may require additional request parameters, so review the API for whatever ajax method you choose. Again, there are libraries like Axios that can abstract/simplify/expand the fetch API for you, or you can just use it directly. Biggest thing to remember is that you can't access the return values until you actually have them, so if you are unfamiliar with Promises then you should also study up on them.
Using Fetch
Promise

Instead of JSON response to POST request, what are my options for React?

Client-side I have a <form method="POST" action="/register"> which makes an SQL query.
Server-side I have this:
router.post('/register', function (req, res, next) {
// code [...]
if (!errors.isEmpty()) {
res.render('register', {
title: 'Registration Error',
errors: errors.mapped()
});
}
}
OK cool, with ejs I have managed to work with the incoming variable errors which is invisible (see next sentence) but my goal is to switch to React. Now, instead of the variable errors I have managed to send a json, but this json appears in the Developer Tools -> Network tab.
I've noticed that third party websites are using POST method with React and I don't see any json in the network tab, so it's either hidden or they use a different method.
Instead of JSON response to POST request, what are my options for React (or if I can hide it)?
If you want to handle the response of a (POST) request in React (or JavaScript) you'll need to send the request via fetch or xhr.
Fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
XHR: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

New line in json array is getting converted to a comma | nodejs

I am relatively new to nodejs and running into an issue while parsing a Json post request.
Here is the JSON format of the post request:
{"parameters":{"issuerId":[96409],"source":["'XYZ'"]}}
And here is my code to read it.
function getSearchData(req, res, next) {
console.log("req is" + req.body);
try {
JSON.parse(reqJSON);
} catch (e) {
console.log(e);
}
}
This parsing works fine and I am able to parse it and do my further logic. However, if I change my format of post request(same request with additional new lines) it fails to parse as it adds additional commas in place of each new line in the request.
{
"parameters": {
"issuerId": [96409],
"source":["'XYZ'"]
}
}
Here's the output from the code with the second request.
req is{,"parameters":{"id":[96409],,"source":["'XYZ'"]}}
[SyntaxError: Unexpected token ,]
If you notice, an extra comma gets added at each new line, which was never in the request to begin with.
What am I doing wrong here?
You should never have to parse the JSON yourself, unless you're concatenating the request body stream yourself.
Hint 1: Do you use any framework like Express? Do you use body parser?
Hint 2: How do you create the JSON?
Hint 3: Do you use correct content-type?
Hint 4: How do you create req.body from the request stream?
You didn't include the entire code so it's impossible to give you a specific solution.
What am I doing wrong here?
Whatever you're doing wrong here, it's not included in the question.
However, if I change my format of post request(same request with additional new lines)
It would be useful if you included more details of how you do it.
I see two potential sources of that problem:
either the commas are introduced during the on the client side
or they are introduced during the request reading on the server side
You didn't show us any of those two parts - you didn't show the serializing code and the code that sends the data, and you didn't include the code that gets the data, possibly joins it from chunks and parses the JSON. But the problem is likely in one of those parts.
Update
Here is an example on how to do what you need using Express. You didn't answer whether you use any framework like Express or not, but I think that you should if you can't achieve that simple task without it, so here is a working example:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
function getSearchData(req, res, next) {
console.log('req body is', req.body);
console.log('req body JSON is', JSON.stringify(req.body));
res.json({ ok: true });
}
app.use(bodyParser.json());
app.use(getSearchData);
app.listen(3335, () => console.log('Listening on http://localhost:3335/'));
It shows how to correctly get a parsed JSON request body as an object req.body, how to print the data as a standard console.log representation and serialized again as JSON. See how it works and compare it to your own solution. This is all I can do because not having seen your entire solution I cannot tell you more than the hints that I've already given.

Can I intercept an incoming request in Express.js before it's handled?

I'm running Node.js with Express.js and everything works perfectly until someone sends invalid JSON with content-type text/json and then my server responds with a 400.
Now, I realize this is "correct" but I'd like to intercept the incoming data and see if I can fix the data by replacing all the new lines (\n \r) with the string representations thereof ("\n", "\r") because that appears to be the problem with the incoming request. Specifically, the json has instances that look like
{"foo":"bar
and so forth"}
Where the line breaks are some combination of \n and \r.
I'm not seeing where I can look-at/massage the incoming request data before it gets bounced as a 400.
This is precisely what middleware is all about. Just insert a middleware handler as the very first handler (before anything else that might look at the request data such as app.use(BodyParser.json())) and it gets first crack at every request and it can modify the request object as it wants to before any of your other handlers see the data.
// make this the first request handler for Express
app.use(function(req, res, next) {
// examine req here and make any changes as desired
// when done, call next()
next();
});
If it's a GET request, the data is all there. If it's a POST request, you will you have to actually read the request stream to get the data before you can process it. This probably means you have to actually replace bodyParser.json() with your own unless you replace the request stream with a new stream.