404 error with GET request with correct credentials - javascript

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

Related

Why is this axios.get request not working>?

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.

Node server to send image to cloud to be hosted

I send an image file to my node server via my react app -
I want to host these images on google cloud or similar so they have an accessible URL.
I have tried using cloudinary and google cloud but to no avail thus far!
My react-side code (shortened):
imageFile = this.state.files[0])
const formData = new FormData()
formData.append('file', imageFile);
sendImage(formData)
sendImage(image) {
axios.post("https://137a6167.ngrok.io/image-upload", image, {
})
.then(res => { // then print response status
console.log(res.statusText)
})
}
The file is successfully sent to my server and consoled:
app.post('/image-upload', (req, res) => {
console.log('consoling the req.body!!!!' + JSON.stringify(req.body))
})
THE CONSOLE: consoling the req.body!!!!{"1":"[object File]"}
I did try use this following cloudinary method, yet it threw errors:
cloudinary.config({
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET
})
app.use(formData.parse())
app.post('/image-upload', (req, res) => {
const values = Object.values(req.files)
const promises = values.map(image => cloudinary.uploader.upload(image.path))
Promise
.all(promises)
.then(results => res.json(results))
})
this gave me the error that an unhandled error in the promise wasnt handled and i got a bit lost with where to go beyond that!
I looked at google cloud storage too but couldn't get it working! Any advice?
What I really want to do is return back to my react app the URL of the hosted image - so it can be stored in DB for the user!
If you can help at all that would be greatly appreciated, thank you.
There are couple of things you need to fix on the front end before you try to upload to any cloud.
First you need to set 'Content-Type': 'multipart/form-data' header in axios to send the file data properly.
Check this thread for more details: How do I set multipart in axios with react?
Then on the express side you need multer or some other similar library to receive the data. You can't access it from req.body. multer adds req.files for example.
https://github.com/expressjs/multer
Try there steps and then post the exact error message you are receiving from google cloud.

Express Server routing issue

I'm trying to add a new route to fetch a user by id but my error handling is not working correctly. Here is the code for that route.
const express = require('express');
require('./db/mongoose');
const User = require('./models/user');
const Task = require('./models/task');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
// ***removed code for brevity
// Route for fetching user by id
app.get('/users/:id', (req, res) => {
//console.log(req.params.id);
const _id = req.params.id;
User.findById(_id)
.then(user => {
//console.log(user)
if (!user) {
return res.status(404).send();
}
res.send(user);
})
.catch(e => {
res.status(500).send();
});
});
So if I test the route on Postman and I enter the correct user id from the database I get that user sent back, which is the the correct response. But if I enter an incorrect user id I get the 500 error code response instead of the 404 error code. The if (!user) statement is getting skipped and I can't figure out why. Any thoughts as to what I am missing?
Running this thru my own personal mongoose/express-using project, I get the following error:
UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "12345" at path "_id" for model "User"
That basically means Mongoose is expecting its own specific object type, an "ObjectId". This is a bit of a pain, since normally if you're using .findOne({_id:something), you can just use a string. If we do:
User.findById(mongoose.Types.ObjectId(_id))
it should work. Note that if you use an invalid id (like I obviously did here, it'll still error out. For that reason, I'd use the standard NodeJS format for callbacky stuff:
.then((err,result)=>{
//other stuff
});
In general, the .catch() block should only happen if obviously Mongoose and your router can't handle it.
EDIT: Also, for others info, Mongoose.model.findById is a built-in convenience method, and should basically do exactly what it says on the tin.

How do I find the id of the current user that is "logged in" with a jwt? I am trying to make a GET request and filter by specific id

This the endpoint in my api that I am trying to access
router.get('/:id', [jsonParser, jwtAuth], (req, res) => {
return Teams.find().sort({creator: req.params.id})
.then(teams => res.status(200).json(teams))
.catch(err => res.status(500).json({message: 'Internal server error'}));
});
The fetch will probably look something like this?
function viewProfile() {
const base = '/api/teams/';
const id = idFromJwt;
const url = base + id;
return fetch(url)
.then(res => res.json())
.then(response => {
//takes response and modifies DOM
populateProfile(response);
})
.catch(err => console.log(err));
}
First of all, assuming you're using ExpressJS I do suggest leveraging express-jwt middleware to handle requests authentication and issuing new Tokens.
What you need to bear in mind is that, you need to include the userId when you authenticate the user in the JWT payload in order to be able to retrieve it from the payload afterwards.
When user is authenticated, you have to store the token in the state of your application or in the localStorage or sessionStorage.
In case you want to decode the token on the front-end side and then send it to the API, you can use a simple module called jwt-decode to achieve that:
const jwtDecode = require("jwt-decode");
const token = window.localStorage.getItem("token"); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWQiOiIxMjM0NTY3ODkiLCJpYXQiOjE1MTYyMzkwMjJ9.gHqSxzWpdOUL1nRAqUJg2CtjsEZZi8FLikD41i639zY
const tokenPayload = jwtDecode(token).id; // "123456789"
Please bear in mind that in case you decided to use express-jwt you need to also send the token in the headers of the request as authorization to authenticate.
Hope it helps. :)

How to handle backend errors from Node/Koa on frontend apollo-client

My frontend, using apollo-client, throws an exception when the backend returns an error after a request.
When the node server receives a request, I check the validity of the request's token using koa middleware. If the token is valid, the request is forwarded to the next middleware. If the token is invalid, I want to return a 401 access denied error to the client. To do this, I followed Koa's error documentation located here.
The code for the error handling middleware I wrote:
function userIdentifier() {
return async (ctx, next) => {
const token = ctx.request.headers.authorization
try {
const payload = checkToken(token)
ctx.user = {
id: payload.userId,
exp: payload.exp,
iat: payload.iat,
}
} catch (error) {
ctx.user = undefined
ctx.throw(401, "access_denied")
// throw new Error("access_denied")
}
await next()
}
}
This seemingly works on the backend, but not on the frontend. When the frontend receives this error, a JavaScript runtime error occurs. I am not sure what causes this.
Note, the unexpected "a" is the same "a" found in ctx.throw(401, "access_denied"). If it were instead ctx.throw(401, "x") the frontend shows "unexpected token x" instead.
The frontend code where the errors happens:
In an attempt to fix this, I followed Apollo's error handling documentation and used apollo-link-error.
const errorLink = onError(props => {
const { graphQLErrors, networkError } = props
console.log("ON ERROR", props)
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
)
if (networkError) console.log(`[Network error]: ${networkError}`)
})
Then I combine all links and create the Apollo client like this:
const link = ApolloLink.from([errorLink, authLink, httpLink])
export const client = new ApolloClient({
link,
cache: new InMemoryCache(),
})
The output of the debugging log in apollo-link-error is as follows:
Related Documents
Someone seems to be having an identical error, but a solution was not listed.
I found that the errors were handled correctly on the frontend when I began using this library on the backend: https://github.com/jeffijoe/koa-respond
Using just ctx.unauthenticated()
But I would still like to know more about how to return json/object-based errors with koa without a plugin helping

Categories