Request works on Postman/Browser, but it doesn't work with axios - axios

I make a GET request to this URL: https://api.mexc.com/api/v3/depth?symbol=BTCUSDT, if I use Postman or just paste it on my browser, it works, but if I use axios like this, it fails:
try {
const { data } = await axios.get(
'https://api.mexc.com/api/v3/depth?symbol=BTCUSDT'
);
console.log('data', data);
} catch (err) {
console.log(`Something went wrong:`, err);
}
You can test it on this link: https://stackblitz.com/edit/js-test-axios-njrh3z?file=index.js
Can someone explain me why please?

Mexc open api required a apikey for use they api.
https://mxcdevelop.github.io/apidocs/#api-key
If you log data response in axios, you will see this in console.
You don't have permission to access "http://api.mexc.com/api/v3/depth?" on this server.<P>\n
Let get an api key then use them api

Related

CORS error: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response

I'm trying to fetch an image resource that's part of a conversation message.
I've tried both FETCH as well as using AXIOS but I'm getting the same error message.
Here's an example of my FETCH request
const token = `${accountSid}:${authToken}`;
const encodedToken = Buffer.from(token).toString('base64');
let response = await fetch('https://mcs.us1.twilio.com/v1/Services/<SERVICE_SID>/Media/<MEDIA_SID>',
{
method:'GET',
headers: {
'Authorization': `Basic ${encodedToken}`,
}
});
let data = await response.json();
console.log(data);
And here's what Axios looked like
let config = {
method: 'get',
crossdomain: true,
url: 'https://mcs.us1.twilio.com/v1/Services/<SERVICE_SID>/Media/<MEDIA_SID>',
headers: {
'Authorization': `Basic ${encodedToken}`,
},
};
try {
const media = await axios(config);
console.dir(media);
} catch(err) {
console.error(err);
}
Both ways are NOT working.
After looking into it more, I found out that Chrome makes a pre-flight request and as part of that requests the allowed headers from the server.
The response that came back was this
as you can see, in the "Response Headers" I don't see the Access-Control-Allow-Headers which should have been set to Authorization
What am I missing here?
I have made sure that my id/password as well as the URL i'm using are fine. In fact, I've ran this request through POSTMAN on my local machine and that returned the results just fine. The issue is ONLY happening when I do it in my code and run it in the browser.
I figured it out.
I don't have to make an http call to get the URL. It can be retrieved by simply
media.getContentTemporaryUrl();

How to tell auth0 im authenticated in req.rest file

So I want to make a post request to my nextJS backend and the route i am making the req to a protected route so in my Rest client file (req.rest) I need to tell auth0 im authenticated but i do not know how to do that.
req.rest
POST http://localhost:3000/api/video
Content-Type: application/json
Authorization: Bearer cookie
{
"title": "Video",
"description": "Video description"
}
api/video.js
import { withApiAuthRequired, getSession } from "#auth0/nextjs-auth0";
import Video from "../../database/models/Video";
export default withApiAuthRequired(async function handler(req, res) {
if (req.method === "POST") {
try {
const { user } = getSession(req, res);
const newVideo = new Video({
title: req.body.title,
description: req.body.description,
ownerId: user.sub,
});
await newVideo.save();
res.json(newVideo);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
});
I'm not sure I understand your question. Your API should determine if the user is authenticated by validating the bearer token value you are passing through the Authorization request header, you shouldn't need to pass additional data as separate parameters to authorize the API. If you do need additional data to determine if the user is authorized to consume the API, that should be included inside of the bearer token as a claim.
So I haven't really found a solution but I do have a workaround which is to just make new page on the frontend for requests and send the requests from there.

how can access to an API which is have a token with Axios in vuejs?

I have an API that has a JSON file, I gonna get information from that with Axios but it has Token and I don't know how can use it anybody can help me?
here it's API
‫‪https://api.nytimes.com/svc/movies/v2/reviews/picks.json‬‬
I try this but its didn't work and gave me error 401 and this
GET https://api.nytimes.com/svc/movies/v2/reviews/picks.json%E2%80%AC%E2%80%AC 401 (Unauthorized)
<script>
import axios from "axios";
export default {
data() {
return {};
},
methods: {
async getDataFromApi() {
const res=await axios.get("https://api.nytimes.com/svc/movies/v2/reviews/picks.json‬‬");
console.log(res.data)
},
},
};
</script>
please, someone helping me
401 Error means you not authenticated. you must add a token in axios authorization header and send it with your HTTP request.
const res = await axios.get('https://api.nytimes.com/svc/movies/v2/reviews/picks.json', {
headers: {
authorization: 'my secret token'
}
});
This is the hard code way, for more efficiency, you must define interceptors for axios to send the token with every HTTP request. see this: https://gist.github.com/srph/38f67a10e991b6cb2d83

Error when trying to authorize Axios get request

I am trying to access the Uber API with Axios and I am running into some trouble. I have plugged this data into Postman and I get a 200 response code with no problems. However, when I try to make an Axios call, I get response code 401 unauthorized. Can I get some help looking through my code to find out why my authorization is not working correctly with Axios?
Here is a link to the Uber API docs I am referencing. Uber API Reference
getRide_Uber = async (addressOrigin, addressDestination) => {
let origin = await geocodeAddress(addressOrigin);
let destination = await geocodeAddress(addressDestination);
const url = "https://api.uber.com/v1.2/estimates/price";
const params = {
params: {
start_latitude: origin.lat,
start_longitude: origin.lon,
end_latitude: destination.lat,
end_longitude: destination.lon
}
};
const headers = {
headers: {
Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
}
};
const response = await axios
.get(url, params, headers)
.then(function(response) {
data = response.data;
})
.catch(function(error) {
console.log(error);
});
return data;
};
Please let me know if anything needs clarification. Thanks!
try below syntax,
const config = {
headers: {
Authorization: `Token ${process.env.UBER_SERVER_TOKEN}`
}
params: {
start_latitude: origin.lat,
start_longitude: origin.lon,
end_latitude: destination.lat,
end_longitude: destination.lon
}
};
const response = await axios
.get(url, config)
.then(function(response) {
data = response.data;
})
.catch(function(error) {
console.log(error);
});
return data;
There is one more aspect axios, async/await is not supported in Internet Explorer and older browsers. So also please check your browser versions as well.
Not sure how are you getting token from env but seems the server token is not getting pass correctly, may be few extra characters while reading from env. Try to run the program first with hard coded token in program itself and once you are sure its not code issue, you can move it into config/env and then debug env read issue.

Service in vue2JS - error in created hook

I'm new to vue2JS and currently I am trying to create my very first service in vue2 ever.
I've created basic file api.js with this code:
import axios from 'axios';
export default () => {
return axios.create({
baseURL: 'http://localhost:8080/',
timeout: 10000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
}
Code above is basic axios configuration which will be used in every service across entire app.
I import this file into my service:
import api from '../api.js';
export default {
getLatest () {
return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`, {
headers: {
'Content-Type': 'application/json'
}
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
}
Code above is responsible for making http request to backend rest API which give JSON in response.
And then finally I want to use this service inside my component <script></script> tags:
<script>
import { getLatest } from '../../../services/articles/getLatest';
export default {
data () {
return {
articles: []
}
},
created () {
const getLatestService = new getLatest();
console.log(getLatestService);
}
}
</script>
Here I want to execute code from service and actually execute this http request then save response in getLatestService constant and then console.log it and I should be able to see JSON in my browser console.
This doesn't work and give me this error in chrome console:
[Vue warn]: Error in created hook: "TypeError: WEBPACK_IMPORTED_MODULE_0__services_articles_getLatest.a is not a constructor"
And this error in command line:
39:35-44 "export 'getLatest' was not found in '../../../services/articles/getLatest'
Please help me to solve this problem. Additionally I want to refactor my code from service (second one) to use async await but I just can't find good example which would show me way to accomplish that.
EDIT 22.11.17
I added error which show in command line and { } when importing in component. I still didn't solve the problem.
EDIT 24.11.17
Looking for an answer I add more explanation of code I've posted and screenshot of files structure if maybe it can help.
I have check your code and what i can see is, in your api.js you have used
baseURL: 'http://localhost:8080/',
and in your service file
return api().get(`http://localhost/obiezaca/ob_serwer/api/article/getLatest.php`
In your service file you have not define your localhost port, i think it should be like
return api().get(http://localhost:8080/obiezaca/ob_serwer/api/article/getLatest.php
If above is not an your issue then you should try
const getLatestService = getLatest();
Because getLatest() is a function and not an object.
This might solve your error issue.