I have the following function (essentially taken straight from the answer to another SO question):
function makePostRequest(requestURL, postData) {
request(
{
url: requestURL,
method: "POST",
json: true,
body: postData
},
function(error, response, body) {
console.log(response);
});
}
When I call it with the right requestURL, I successfully reach this route:
router.post("/batchAddUsers", function(req, res) {
console.log("Reached batchAddUsers");
});
I've been trying to retrieve the postData I sent with the request to no avail. Both req.params and req.body are {}. I haven't got the faintest clue how to refer to the object containing body passed in the request.
I read the whole console.log(req) and found nothing useful. I've done this kind of stuff before, except the request was made by a form and req.body worked like a charm. Now that I'm doing the request "manually", it doesn't work anymore. The whole thing is running on Node.js.
What am I doing wrong?
I think you did not insttalled body-parser
To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser.
body-parser extract the entire body portion of an incoming request stream and exposes it on req.body .
The middleware was a part of Express.js earlier but now you have to install it separately.
This body-parser module parses the JSON, buffer, string and url encoded data submitted using HTTP POST request. Install body-parser using NPM as shown below.
npm install body-parser --save
Related
I've created a basic app which can take notes, and I'm using a .json file to store them. This is part of an assignment where I was given the front-end code and then had to create the Express back end.
Throughout development I used nodemon to run the server, but I needed to host on heroku so I've changed it to start with node instead, however now my GET requests in the fetch method are returning 304, even when the database has definitely been modified. POST and DELETE both still work and modify the database but GET doesn't even after refreshing the page. I have to stop the server and start it again for the fetch request to work.
The code making the request:
const getNotes = () =>
fetch('/api/notes', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
Express code used to respond:
app.get('/api/notes', (req, res) => res.json(database));
Any help is much appreciated.
Note: I explain the strange urls in a spoiler below.
Electron#2.0.4
jquery#3.3.1
When I try to use $.ajax to an absolute path from within Electron jquery seems to get rid of my payload. I use the following:
$.ajax({
url: "/test/anything?func=ajax",
method: "POST",
processData: false,
contentType: "application/json",
data: JSON.stringify({foo: "bar"}),
});
fetch("/test/anything?func=fetch", {
method: "POST",
mode: "cors",
body: JSON.stringify({foo: "bar"})
});
They produce the following requests:
As you can see, the ajax call has no payload while the fetch does. Does anyone know a way to fix this or if there is a reason for this behavior?
As for the strange URL, I use a service worker to forward urls that start with /test to http://localhost, that's working properly as pictured below. Localhost is just for testing, I have a local copy of httpbin running on docker.
I am doing this to port a web app to electron so the codebases can be the same, aside from index.html changes and adding sw.js.
Thanks to Rory's comment above, I found a solution. I installed express and added the an express.js file to the project root, with the contents:
const express = require('express')
const app = express()
app.use(express.static('.'))
app.listen(3000)
Using this gist, I added the following to various places in my main.js file:
const express = require('./express.js'); //<
function createWindow () {
mainWindow.loadURL('http://localhost:3000/index.html'); //<
}
The service worker still gets the request, and it replaces the http://localhost:3000/test with http://localhost
ajax:
service worker:
The service worker also sends an OPTIONS request to make sure cross domain is allowed, while the fetch's request doesn't. This seems to be because the ajax request has an X-Requested-With header, while the fetch doesn't.
Background
I have a NUXT application that renders vue templates as you would expect. I have a need to hit some Express routes in the application from external applications client side.
I can hit GET routes from external applications but POST requests fail with a error 404.
Example
Express
This works
router.get('/test/get', (req, res, next) => {
res.json({ message: "Global PDF Generator is configured correctly", status: "operational" })
});
This fails with 404
router.post('/test/post', (req, res, next) => {
res.json({ message: "Global PDF Generator is configured correctly", status: "operational" })
});
Inside of the Nuxt application and within any of the vue components I can hit the POST routes like this,
fetch('api/v1/pdf', { method: 'POST' }
But if we try to do something like this it fails,
fetch('localhost:3000/api/v1/pdf', { method: 'POST' }
The second example is important because obvioulsy that is how I would have to hit an end point in this application from an outside application.
What I can not figure out is why the GET requests work and do not get a 404 while the POST requests continue to get a 404 from external applications.
Question
How can I create an externally accessible Express POST end point in my NUXT application so that it will be directly accessible from an external source?
Not as an answer but just so I can format things and demonstrate that something else must be going on. This minimal example works fine for me.
vue init nuxt-community/express-template sample_post
cd sample_post
npm install
Modify api/routes/users.js adding a post route:
router.post('/test', function(req, res, next) {
res.json(message: 'hello');
});
Start up the service:
npm run dev
Verify it returns a post from an external request successfully:
curl -X POST http://localhost:3000/api/test
{"message":"hello"}
So something else must be going on somewhere.
This is because when the NuxtJs app on production it sees only page routes not server route. You should use NuxtJs serverMiddleware. You can find it here from NuxtJs API
I am trying to download an image from a server through an https proxy, please help.
My code:
var request = require('request');
request({
url: url,
proxy: proxy
}, function (err, res, imgBuffer) {
console.log(err)
console.log(res)
})
The error:
Error: tunneling socket could not be established, cause=write EPROTO 101057795:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:openssl\ssl\s23_clnt.c:827:
I can provide any additional info needed, I have already tried a lot.
I'm thinking you need to change the config file in npm.
Check out this tutorial: https://www.jhipster.tech/configuring-a-corporate-proxy/
Go down to the section titled "NPM configuration."
I am trying to fetch a rss feed from our staging site and at present it has htpasswd security on it.
I have tied using the format:
http://username:password#url.com
This works on the browser but when I try to do this with nodejs it fails.
Could you tell me what is the right way to do this with node.js.
app.js
var request = require('request');
request.get('http://url.com', callback).auth('username', 'password', false);
function callback(err, response, body) {
console.log(body);
}
terminal:
npm install request
node app.js
document: https://github.com/mikeal/request