Problem: I'm trying to connect an API url link through another API function.
API Url (Provided by Third Party): http://garden.home.com:8080/api/GetAllHome
API Link (Created by me): http://localhost:3000/town/house
The API link created by me is just meant to be a API function which will contain the provided API url. I'm trying to connect to the API provided thought my function but I'm encountering problems.
I've tried using http.get and axios.get but I've encountered several problems
Using http.get
Error: getaddrinfo ENOTFOUND garden.home.com garden.home.com:8080
"message": "http.get(...).then is not a function"
app.get('/town/house', (req, res, next) => {
http.get(allHouseUrl)
.then(response => {
console.log(response.data.url);
console.log(response.data.explanation);
})
.catch(error => {
console.log(error);
});
});
const allHouseUrl = {
host: 'garden.home.com',
port: 8080,
path: '/api/GetAllHome'
}
I tried the online solutions, which was to wrote their url details in an object and call it.
Using axios.get
Error: getaddrinfo ENOTFOUND garden.home.com garden.home.com:8080
app.get('/town/house', (req, res, next) => {
axios.get("http://garden.home.com:8080/api/GetAllHome")
.then(response => {
console.log(response.data.url);
console.log(response.data.explanation);
})
.catch(error => {
console.log(error);
});
});
My desired results would be to connect to the provided url link and be able to pass parameters to it.
I am able to to retrieve the json data from http://garden.home.com:8080/api/GetAllHome by using Postman but I am unable to access it through an API function that I created.
Related
Earlier, I was able to pipe the response of another api call to Next.js api response as follows
export default async function (req, res) {
// prevent same site/ obfuscate original API
// some logic here
fetch(req.body.url).then(r => {
r.body.pipe(res);
}).catch(err => {
console.log(err);
res.status(500).send("Invalid Url");
})
}
It worked fine. But now the response.body from fetch API does not have pipe method. Rather, it has pipeTo and pipeThrough methods. And the Next.js res:NextApiResponse, is not assignable to WritableStream.
I also tried creating blob (await r.blob()) and using res.send(blob) and res.send(blob.strem()). It seems to work at first but the data received by front end is not proper (Basically fetch().then((res) => res.blob()).then((blob) => URL.createObjectURL(blob))) will give corrupt result).
my api call isn't sending to the proxy url domain. I know that it isn't calling as the console.log in the server isn't going off. Could someone please help me?
//client package.json
"proxy":"http://localhost:3001"
//client app
useEffect(() => {
const apicall = async () => {
try{
const response = await fetch("/")
if (response.status !== 200){
throw new Error()
}
else{
console.log("api call was success")
console.log(response)
}
} catch(error){
console.log(error)
}}
apicall()
}, [])
//server
app.get("*", (req,res)=>{
console.log("apicalled")
res.cookie("refreshToken", 987654321, {
maxAge: 60000,
httpOnly: true
})
res.send("has cookie sent?")
})
Don't have an answer for you, but it looks like you're using create-react-app? I think if you've setup your own server, you don't need to set the proxy in your package.json.
I am running a small react app and trying to access an external api behind my company's proxies. I continue to get the cors error - I've tried setting a proxy in package.json and using setupProxy.js (separately), but haven't had any luck.
Background: I am building a chrome extension that sends a simple http request and should be able to work with ssl client authentication.
Goal: Send a fetch request to a site with ssl client authentication without user having to open the site first.
What happens so far:
The request is only successful after i open the site manually.
Attempted using credentials: 'include' as suggested here - didn't solve the issue.
Im getting TypeError: failed to fetch
Fetch API docs # Mozilla don't seem to mention this (here and here)
fetch is sent as follows:
fetch(url)
.then(response => {
if(!response.ok){
throw Error("Http request failed");
}else{
return response
}
})
.then(response => response.text())
.then(validate => validate.replace(/\D/g,''))
.then(count => {
chrome.action.setBadgeText({text: count});
if(callback){
callback();
}
})
.catch(error => {
console.log(error)
if(callback){
callback();
}
});
I would be very grateful if you could guide me on what might be the issue.
I'm working on a personal project that will allow users to find new books based on their preferences for the genre. The database I'm using is MongoDB. However, while I'm able to get all the data on the backend using Postman, I can't get it properly displayed on the frontend. At the moment, I'm just trying to get the data sent to the front end and at least console.log'd but it isn't making it that far.
Here is the code in the routes file.
router.get('/books/:genre', bookBuilder.get_some_books)
Here's the code on the backend that the routes file is pointing to and is working:
exports.get_some_books = async function (req, res) {
let { genre } = req.params;
try {
let books = await Book.find({"genre": genre});
if (books) {
res.json(books)
} else {
res.status(404).send({error: 'Not Found'});
}
} catch (err) {
res.status(500).send({error: err.message});
}
}
Here's my code on the frontend that is not working.
async getEverything() {
try {
let pbBooks = await axios.get(`/books/`, {
method: 'GET',
headers: {'Content-Type': 'application/json'},
params: {
genre: 'PB'
}
})
if (pbBooks) {
console.log(pbBooks)
} else {
this.$router.push('/Error');
}
} catch (err) {
console.log(`Network error: ${err.message}`)
}
}
My code stack is Vue.js, Express.js, Node.js and Axios. On the frontend, I've tried making the inner code of axios.get() into '/books/PB' and then tried getEverything(genre) along with /books/${genre} but neither seems to be working.
The error I am getting is a 404 Request Failed error that is from the catch block in the getEverything() function. I'm not sure why the frontend is unable to get the data when the backend works just fine. Is there anything I'm doing wrong?
404 is the HTTP status code for Not found, which implies there is no route setup on localhost for /books. Actually, /books would route to your app, not the backend (unless you have a proxy setup on your app server that redirects to the backend).
If a proxy were involved, it's likely misconfigured. Otherwise, the target URL in the Axios request should be <backend_url>/books (e.g., http://localhost:9999/books with the back running locally on port 9999, and the app on some other port).
Change
let pbBooks = await axios.get(`/books/`, {
...
to
let genre = "PB"
let pbBooks = await axios.get(`/books/${genre}`, {
method: 'GET',
headers: {'Content-Type': 'application/json'}
})
reason is the params part of the config object is converted to query strings (/books?genre=PB) instead of /books/PB, which is what the backend is expecting
More: https://masteringjs.io/tutorials/axios/get-query-params
I have the following simple GET inside a function.
axios
.get(`/api/search/q=${this.value}`)
.then(res => {
console.log(res.data);
});
The GET 404's if I enter a query (the letter 'a' in this case):
GET http://localhost:7777/api/search/q=a 404 (Not Found)
so, of course I get an Uncaught promise error from the .then:
Uncaught (in promise) Error: Request failed with status code 404
I figured that it must be a simple routing problem, but my express route is:
router.get('/api/search', someController.someFunction)
The function in the controller works (ie responds with the data) as I have used it elsewhere in the app, so I feel that I have narrowed it down to the axios GET not finding the api. But I can't figure out why, as the path looks OK to me.
You were 404 getting because node is expecting only /api/search but your trying /api/search/:q which is different altogether, try
axios.get('/api/search/', {
params: {
q: value
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
since any number of parameters added will not make the URL clumsy, an alternate for
axios.get('/api/search?q=${this.value}').
and on the server
router.get('/api/search', someController.someFunction)
and in your controller
if(req.query.hasOwnProperty('q')){
var q = req.query.q;
}