In my NodeJS/Express app, I have API implementation which calls another external API.
For this, I am using npm request & request-promise libraries
How can I call API's that has path parameter?
const express = require('express');
const router = express.Router();
const rp = require('request-promise');
router.post('employee/:id', (req, res) => {
const id = req.params.id; // I dont know how to use this in request library
handleRequest(req, res);
})
function handleRequest(req, res) {
const id = req.params.id; // I dont know how to use this in request library options?
var options = {
method: req.method,
uri: 'http://api.anotherhost.com/external/'+ req.path,
body: req.body,
qs: req.query,
json: true
};
rp(options)
.then((success) => res.send(success))
.catch((err) => res.status(err.statusCode).send(err.message));
}
https://github.com/request/request
https://www.npmjs.com/package/request-promise
Update:-
This code so far works fine for other calls without path parameter.
Since request doesn't provide an option to add path parameters you have to format your request uri to include them, you can simply use string literals to do this:
const id = req.params.id;
var options = {
method: req.method,
uri: `http://api.anotherhost.com/external/${id}`,
body: req.body,
qs: req.query,
json: true
};
Keep in mind you must verify that the id format is valid.
Related
I can't receive files when using https on express but works well when using only http. I just updated my express app to use a self-signed certificate for testing.
Here's what I am trying:
upload function
exports.upload = async (req, res) => {
console.log(req.file); //returns undefined
console.log(req.body.file); //returns [Object: null prototype] {}
...REST OF CODE...
}
client function
const formData = new FormData();
formData.append('file', pdfFile);
formData.append('user', 'test');
const params = {
body: formData,
method: 'POST',
credentials: 'include'
}
const result = await fetch('https://localhost:3000/service/upload', params);
I also noticed that the content-length is set to "0" when inspecting the network tab. Payload tab is also missing.
Request headers
I want to use a third-party api: Latin WordNet API, but I meet some problems.
The api document shows how to get result by url in browser, but I don't know how to get result by other way.
I try to use axios through HTML script element to get the result, like:
const btn = document.querySelector('#searchBtn')
btn.addEventListener('click', function () {
const options = {
method: 'GET',
url: 'https://latinwordnet.exeter.ac.uk/api/lemmas/virtus/n/'
}
axios(options).then(data => console.log(data))
})
But I get error about CORS. If I use proxy like ngrok, it still doesn't work.
3. I want to try it like normal route, like:
const express = require('express')
const router = express.Router()
router.get('/api/lemmas/virtus/n/', (req, res) => {
console.log(res)
})
I don't know where the result will come from, and I'm also not sure this way is right or false.
Hope anyone may give some tips.
try with GET request:
const options = {
method: 'GET',
url: 'https://latinwordnet.exeter.ac.uk/api/lemmas/virtus/n/'
};
axios(options)
.then(response => console.log(response.data.results))
.catch(err=>console.log(err.response.data));
I found a way to deal with it:
const express = require('express')
const axios = require('axios')
const router = express.Router()
router.get('/search', (req, res) => {
axios.get(`https://latinwordnet.exeter.ac.uk/api/lemmas/${req.query.word}/n/`)
.then(response => {
return res.json(response.data.results)
})
})
combine route and axios
This question already has answers here:
How to access the request body when POSTing using Node.js and Express?
(15 answers)
Closed 2 years ago.
I am trying to send a post request using Axios and I also want to access the data from the server. My code is
axios({
method: 'post',
url: '/register/',
headers: {'Content-Type' : 'application/json'},
body: JSON.stringify({fname, lname, username, email, pass})
})
.then((res) => {
console.log(res)
})
.catch(err => {
console.log(err)
})
// and my backend code is
const express = require('express')
const router = express.Router()
router.post('/', async (req, res, next) => {
const firstname = ''
})
Request is send properly and my server also accepts the request. but i do not know how to get the values from my server.
please help me. code is working fine just help me in getting the values on server side code
Unlike fetch, axios does not require you to stringify the body of the post request. You can just post like so:
axios({
method: 'post',
url: '/register/',
headers: {'Content-Type' : 'application/json'},
body: {fname, lname, username, email, pass}
})
...
Assuming you are posting to the correct endpoint (e.g. /register), on the server side, you would access it this way:
router.post('/register', (req, res) => {
const fname = req.body.fname;
...
})
Note that this assumes your backend is properly configured. If all you're running is the code you showed, it won't work as you would need stuff like:
const app = express();
app.use(express.json());
...
...
app.listen(YOURPORT, () => {
console.log(`Listening to requests on port YOURPORT...`);
});
I want to make a http PUT request with zip file in binary to a web api and get response with http status code.
How to read the file and PUT it with binary ?
Thank you for your help!!
You can start with this:
var http = require('http');
var fs = require('fs');
var req = http.request({
hostname : HOSTNAME,
port : PORT,
path : UPLOAD_PATH,
method : 'PUT',
});
fs.createReadStream('somefile.zip').pipe(req);
You may need to perform some other actions, like proper error handling, setting Content-Type headers, etc.
Using request-promise (based on bluebird)
const fs = require('fs');
const request = require('request-promise');
const options = {
method: 'PUT',
url: 'dest url',
qs: {key: 'value'}, // optional
headers: {
'content-type': 'application/octet-stream'
}
};
fs.createReadStream(zipFilePath).pipe(request(options)).then(body =>{
console.log(body);
})
.catch(err => {
console.log(err);
});
Check that answer.
The only difference would be, you are using .put() instead on .post().
I have the following code:
var express = require('express');
var app = express.createServer();
var request = require('request');
app.use(myMiddleware);
app.listen(5010);
var payload = { id: 1 };
request({
method: 'POST',
body:JSON.stringify(payload),
url: 'http://localhost:5000'
}, function(err, res, body) {
console.info("Request Done");
})
In my middleware code I want to parse the body and extract the request id, yet for some reason the following code doesn't work (payload is undefined):
var myMiddleware= function (req, res, next){
var payload = req.body;
if (payload.id === 1) console.info("first request!!!!!");
next();
}
When I try to print "payload" all I get is [object Object].
Could you please tell me how to extract the id, and how to print the attributes of the payload object?
Thanks,
Li
Solved by adding:
app.use(express.bodyParser());
and by adding the following to the request code:
json: true
After adding the json=true attribute I also removed JSON.stringify(...) from the body of the request (now I don't need to stringify the body since it expects a json object)
Thanks.