Why is this axios.get request not working>? - javascript

I am currently doing Colt Steele's Web Developer bootcamp and have came across this issue...
In this particular tutorial we are using axios as 'request' has since become discontinued so I'm trying to follow along with this.
What I want to do is set up a Get route for a '/results' page, in this I want to pull information from the OMDB Movie Database and just now, simply show the JSON file when I go onto this Url.
I'm sure there's an obvious solution but I can't seem to figure it our after having searched for hours.
Here is my code;
const express = require('express');
const app = express();
const axios = require('axios').default;
app.listen(3000, () => {
console.log('Im listening');
});
app.get('/results', (req, res) => {
axios.get('http://www.omdbapi.com/?t=california&apikey=thewdb')
.then((response) => {
res.send(response);
}).catch((err) => {
console.log('This isnt right');
})
});
As you can see I am also using express, everything is installed correctly. In fact, when I do a console.log(response) like so:
axios.get('http://www.omdbapi.com/?t=california&apikey=thewdb')
.then((response) => {
console.log(response);
}).catch((err) => {
console.log('This isnt right');
})
It works, I can see the API JSON in my console, which makes me think there is a problem with using res.send(response) in the promise.
Any help would be greatly appreciated. Apologies if I've missed any info out, still fairly new to this...

To get response data for a OMDb request use data property:
app.get('/', function (req, res, next) {
axios.get('http://www.omdbapi.com/?t=california&apikey=thewdb')
.then(result => res.send(result.data))
.catch(err => res.send(err));
});
For more information, see Axios's Response Schema documentation.

Related

Express/axios don't set cookies and headers for response

I have very complicated problem. My project has 2 API's. 1 API is for front-end of my application and 1 is for back-end. How it works, is just I send request from front-end API to back-end API.
Front-end API has URL http://localhost:8080/api/ and back-end API has URL http://localhost:3000.
The problem is front-end API can't get cookies from back-end API.
Here is example, function of front-end API just send request to back-end:
router.get('/test-front-api', async (req, res) => {
const data = await api.get('/test-back-api')
return res.json(data.data)
})
Back-and just sends cookie and some random text:
router.get("/test-back-api", (req, res) => {
res.cookie("test", "cookie")
res.send("Hi from back-end")
})
A here is where I have problem:
router.get('/test-front-api', async (req, res) => {
const data = await api.get('/test-back-api')
console.log(data.headers) // If you do console.log here you will this cookie test
return res.json(data.data)
})
But this cookie is not set in browser.
Let me show one more example. In browser I can just type http://localhost:8080/api/test-front-api and here is result, no cookie:
But, if I type not front-end API endpoint, but back-end, everything works perfect:
I was trying literally everything I found about cors options, axios {withCredentials: true} etc. Nothing works.
I have found one solution, but I don't like it:
router.get('/test-front-api', async (req, res) => {
const data = await api.get('/test-back-api')
// Something like this
res.cookie("test", JSON.stringify(data.headers['set-cookie']))
return res.json(data.data)
})
So, my question is why cookie is no set by front-end endpoint?
I have found not reason of the problem, but solution that seems to be ok. As I said, there are 2 API's - front-end and back-end.
From back-end API I get this cookie, but actually, it makes no sense to send it in header. Why? Because the front-end API will send it back on front.
So, using example above, you can do this, first, just send this cookies in body:
router.get("/test-back-api", (req, res) => {
res.json({cookie: "cookie"})
res.send("Hi from back-end")
})
And then, in front-end API, handle it:
router.get('/test-front-api', async (req, res) => {
const data = await api.get('/test-back-api')
res.cookie("test", data.cookie)
return res.json(data.data)
})
But I still have no idea, why I can send the same headers twice, through back-end API, then front-end API and finally on front.

How we can intergrate Qr code monkey api to an express.js backend

Intergrate this for https://rapidapi.com/qrcode-monkey/api/custom-qr-code-with-logo
For this code
const express = require('express');
const http = require("https");
const router = express.Router();
router.post('/',async (req,res)=>{
console.log("req",req.body);
return res.sendStatus(200);
});
module.exports = router;
I'm not sure the question you're asking here.
My guess is that you're trying to interact with the qrcode-monkey API using express.js?
If that's true, following the qrcode-monkey API documentation you'll have to invoke (in this case) express to issue either a GET or POST request to the correct end point /qr/transparent with the required data both in the request body and head. this is documented in the link you provided
since you're doing this via express it's I assume you're going to be passing the URL that the qr code points to via your endpoint then to the 3rd party API. This might looking something like this.
router.get('/:url', async (req, res, next) => {
if (!req.params.url) next(new Error('400 missing url param'))
try {
res.body.qr = await fetch('https://qrcode-monkey.p.rapidapi.com/qr/transparent',
{
method: 'GET',
headers: { ... },
body: { ... }
}
).json()
} catch (error) {
next(error)
}
res.json(req.body.qr)
})
note: this is pesudo code and shouldn't just be copy/pasted.
I suggest refering to the express.js documentation
This question seems to go into more detail about 3rd party API interation with express.

How do I fetch on an update to a url containing JSON?

I am running a couple of arduino mini's who send JSON data to a url-path on my website. Currently I have managed to fetch the data just fine, but would like to fetch upon JSON changes to the url, instead of fetching every x seconds.
Code for the fetch part:
async function getMini4 () {
let response = await fetch('/api/sensor/mini4')
let data = await response.json()
return data
}
And the Express that posts the formatted json:
app.get('/api/sensor/mini1', (req, resp, next) => {
resp.send(gyroData1)
})
app.post('/api/sensor/mini1', (req, resp, next) => {
gyroData1 = req.body
resp.send()
})
The fetch works just fine, but I can't seem to find anything on fetching when the url changes.
Are you familiar with websockets ? This protocol allow you to push update from the server to the client and it seems to exactly fit your need.

404 error with GET request with correct credentials

I have switched my node package to the official shopify-api-node one and now the request isn't working it returns a 404 error.
The requests parameters seem to be fine after looking at the docs, and the shopName, access token etc are also correct i used the identical ones for the last package, (shopify-node-api) which i only stopped using because it returned a body in a strange coded language so i couldnt check it for errors, anyway here is the code:
The 'name' value is the order number by the way.
getOrderByNum: (req, res) => {
// const domain = req.params.domain;
const domain = 'chatbotdemo.myshopify.com'
const name = req.params.name;
console.log(req.body)
db.getStoreTocken(domain, (result) => {
const shopify = new Shopify({
shopName: domain,
accessToken: result,
autoLimit: true
});
shopify.order.get(name)
.then(order => {
console.log('console the order??!?!?!');
})
.catch(err => console.error('error??' + err));
Any help would be greatly appreciated,
the shopify docs:
https://www.npmjs.com/package/shopify-api-node

Post data is not being recieved

I am trying to test my newly written api to send messages. It catches a message and sends it to a database. I am using https://apitester.com/ to test it. When I try to read req.body, I get undefined.
SERVER
app.route('/message')
.post(createMessage);
var createMessage = (req, res) => {
console.log(req.body)
var newMessage = new Message(req.body)
mlab.insertDocument({database:'databasename', collectionName:'collectionname', documents:newMessage.getCreatePack()})
.then(result => {
res.json(result)
})
}
When I try to log(req.body), I get undefined
This is the request data. Any help is appreciated
As it turns out, I need body parsing middleware, such as body-parser.

Categories