node-fetch GET with a parameter - node.js

I want to get a url with "username" paramater in it.
How can i do it?
Example:
get url: api/find-username
paramater: username: "exampleusername"
Is it possible with node-fetch module?

Yes, it is possible as node-fetch can construct just about any http GET request the server could want.
What you need to know from the target server is how the username parameter is supposed to be delivered. You can construct the request in node-fetch, but you have to construct it in the way that the target server is expecting (which you have not described).
For example, if the username is supposed to be in a query parameter and you're expecting JSON results, then you might do it like this:
const fetch = require('node-fetch');
// build the URL
const url = "http://someserver.com/api/find-username?username=exampleusername";
fetch(url)
.then(res => res.json())
.then(results => {
console.log(results);
})
.catch(err => {
console.log(err);
});
I will mention that constructing the proper URL is not something you guess on. The doc for your target server has to tell you what type of URL is expected and you must construct a URL that matches what it is expecting. It is typical to put parameters in a query string for a GET request as shown above, but when there is one required parameter, it can also be put in the URL path itself:
const fetch = require('node-fetch');
// build the URL
const url = "http://someserver.com/api/find-username/exampleusername";
fetch(url)
.then(res => res.json())
.then(results => {
console.log(results);
})
.catch(err => {
console.log(err);
});

Related

Why am I am Getting a Typeerror: res.send is not a function with Axios. Res.send works outside the res.send but I need the data from the API

enter image description here
I need to get data from this api endpoint, and send it to my client (React). Everything works fine between the frontend and backend, but I cant seem to figure out how to get the data within /dailyscores endpoint and send it using axios. Any help on why res.send is not a function inside .then, and a way to get it work?
The way you are using res as argument name for both express and axios callback is the issue here.
app.get('...', (req, res) => {
axios.get('...').then((res) => {
res.send(res.data); // here the res of axios.then is used
})
});
Instead use different names
app.get('...', (req, res) => {
axios.get('...').then((response) => {
res.send(response.data);
})
});
checkout variable scopes for more info
To get data from API please try as below:
const [apiResp, setApiResp] = useState([]);
useEffect(() => {
axios.get(`<api>`)
.then(res => {
const response = res.data;
setApiResp([response]);
})
});

Mongoose response from server is ReadableStream

I have an express server that is fetching data from a local MongoDB.
The fetching seems to work and I am able to log the fetched data:
app.get("/getTestData", async (req, res) => {
const data = await ContentDataSchema.find();
console.log(`Mongo data: ${data})`);
res.json(data);
});
This prints on the server console the correct data from DB which is expected to be an array of objects of the ContentDataSchema.
However, when trying to get this data from the client side:
useEffect(() => {
fetch("http://localhost:7007/getTestData")
.then((response) => {
console.log(`RESPONSE ${response.body}`)
})
.catch((error) => console.log(`SERVER ERROR ${error})`));
}, []);
Console output from this is RESPONSE [object ReadableStream]
And if I tried to to log console.log(RESPONSE ${JSON.stringify(response.body)})
Then the output is just {}.
Using Postman I can see the correct expected response calling the same endpoint.
Expected output on the client side would be the actual json from the DB.
To read the JSON response, you have to use the response.json() method. You can refer to the MDN docs about fetch to learn more about it.
fetch("http://localhost:7007/getTestData")
.then(response => response.json())
.then(data => console.log(data));

NodeJs, Axios: Value of variable not updating with response from xhr request

I am making an xhr request in nodejs using Axios. And I am trying to save a value from this response to a variable, but it isn't working and I am not sure why.
Code:
let redirectUrl = 'placeholder'
axios.get(url)
.then(res => {
redirectURL = res.url
console.log(res.url, "HERE")
})
.catch(err => console.log(err))
return res.render('index',{url: redirectURL})
I have tried declaring redirectUrl in both global as var and local scope, but the value isn't changing, on index when I console log this value, it logs placeholder. index is index.jsx as I am using jsx as the template engine.
Please let me know if I should provide any more information.
Thank You in advance.
axios.get is an async call, so your return will use the original (placeholder) value instead of the new one. Normally to solve this kind of asynchronicities i use async/await
async function getRedirectURL(url) {
try {
const res = await axios.get(url);
// Note that if you want some return value from axios call you access it by res.data
console.log('res.url :', res.url, ". res.data:", res.data);
return res.render('index',{url: res.data.url});
} catch (err) {
console.log(err);
throw err;
}
}
Axios is a promise-based HTTP client, So when javascript engine executes your code, it moves axios call to web API from callstack (line# 2) and then it starts to execute the last line return res.render('index',{url: redirectURL}) where redirectURL value is placeholder. You have to write all the logic in promise then method, like
axios
.get(url)
.then((data) => res.render("index", { url: data.url }))
.catch((err) => {
// error response
console.log(err);
});

How to post a url

I am trying to convert an image to a url and then post it to a database using axios.post like this:
this.setState({
file: URL.createObjectURL(event.target.files[0])
})
and then posting it like so:
axios
.post(`http://localhost:4000/items/${this.state.file}
my model is this:
let items = new schema ({
img: String
})
and my post controller:
router.post('/:urlImg', function (req, res) {
let b= new items ({
imageProof: req.params.urlImg
})
the error is basically POST 'url' 404 (Not Found):
xhr.js:184 POST http://localhost:4000/items/blob:http://localhost:3000/9045e921-4e7f-4541-8329-0b9cd65814c6 404 (Not Found)
however the thing to note is if I am using a simple url such as www.google.com, it works. however, I can't use https://
does anyone know how I can resolve this problem? Is there some other way to store and display an image?
You can simply url encode your image url as follow. When you just pass the url without encoding it first it forms a invalid url which contains https in the middle. So you have to encode it before passing
axios
.post(`http://localhost:4000/items/${encodeURIComponent(this.state.file)}
Or
Instead of sending it as a url parameter send it as a body parameter
axios.post('/user', {
urlImg: "http://your/image/url"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
For 2nd approach you might want to change the backend in order to extract the parameter from the request object.

How to add id and body to axios.PUT request?

I am using axios with REACT and wondering how I can use it to make a put request to update an object through the backend node/express API I have set up.
I need to be able to pass an id and a body and not sure of how to do so.
axios.put('/api/profile', id, body)
.then(response => {
console.log(response.data);
})
.catch(err => {
console.log(err);
});
I do not think this will work as it takes the parameters of put(url, data, {headers})
The pattern for this is to making an axios request using the id of the entity/item that you want to update and return as shown:
axios.put(`/api/profile/${id}`, body); //using string interpolation
axios.put('/api/profile' + id, body); //using string concatenation
Then, on your express/node backend, you have a route that will match with this request's URI path and update that profile with the body. Not sure what you're using for your DB, but in pseudocode it would look like this:
/*
* 1. query profile Model for the specific profile
* 2. make sure to check if foundProfile is undefined or not.
* 3. update profile with body
* 4. Catch on errors
*/
router.put('/api/profile/:id', (req, res, next) => {
Profile.findbyId(req.params.id)
.then(foundProfile => foundProfile.update(req.body))
.catch(next);
})
As mentioned in a comment above, you could do this via the query string, but that would be odd/anti-pattern.

Resources