GET http://localhost:3000/api/eventNames net::ERR_CONNECTION_REFUSED - vue.js

I am trying to get axios working with my vue project so I can test the backend of my app. It seems that I am having issues setting up the axios server as I'm getting a connection refused on the baseURL that I have setup. I posted my api.js file that I created under service/api.js. Any information on things to look at to get this resolved would be greatly appreciated.
/src/service/api.js
import axios from 'axios';
export default () => {
const instance = axios.create({
baseURL: 'http://localhost:3000/api',
withCredentials: false,
headers: {
Accept: "application/json",
"Content-Type": "application/jason"
}
});
return instance;
}

Related

NuxtJS - manage several axios instances

I use NuxtJS 2, and I need to have 2 or more axios instances with different configs.
In VueJS / JS classic, I can just create a new instance of axios:
var axiosElasticSearch = axios.create({
baseURL: 'https://elastic.com/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
But in Nuxt, they apply their own config to handle this, because of the SSR layer.
In my Nuxt config, I have this :
axios: {
baseUrl: process.env.API_URL,
browserBaseUrl: process.env.BROWSER_API_URL,
withCredentials: true,
headers: {
common: {
Accept: 'application/json',
Authorization: 'Bearer ' + process.env.API_TOKEN
}
}
},
And then, I can inject it easily.
Is it possible to manage it in Nuxt? I looked at proxy option, but I don't think it's what I want.
nuxt/axios allows creating new Axios instances with $axios.create, which takes the Axios config from nuxt.config.js into account.
For example, you could create a Nuxt plugin that injects a new Axios instance into the root context:
// ~/plugin/api.js
export default function ({ $axios }, inject) {
// Create a custom axios instance
const api = $axios.create({
headers: {
common: {
Accept: 'text/plain, */*'
}
}
})
// Set baseURL to something different
api.setBaseURL('https://my_api.com')
// Inject to context as $api
inject('api', api)
}
And configure your Nuxt app to use it:
// nuxt.config.js
export default {
plugins: ['~/plugins/api.js']
}
Then your component could use the new Axios instance:
// MyComponent.vue
export default {
fetch() {
this.$api.get(...)
},
asyncData({ $api }) {
$api.get(...)
}
}

set mobx store in const value in react native

how can i set const value using mobx obeserve data? as i don't know how can i define props here.
export const BASE_URL = base_url_from_mobx
i have some data in this function. From there i will have some confidential data and a base url. This ApiKeys is a native module
ApiKeys.getApiKeys((data)=>{
let secureData = JSON.parse(data)
}
i have an api.js file where i set the interceptor and set the base url like below
const api = axios.create({
baseURL: BASE_URL,
timeout: 10 * 1000,
headers: {
'content-type': 'application/json',
}
});
here BASE_URL is defined and export as const in constants.js file but now i want to set it from the value i have got from the function.
This can be done if i can do like below
const api = axios.create({
// baseURL: BASE_URL,
baseURL: (JSON.parse(AsyncStorage.getItem(SECURE_KEY))).SOHOJ_APP_API_BASE_URL_DEVELOPMENT,
timeout: 10 * 1000,
headers: {
'content-type': 'application/json',
}
});
but it is giving me issue like
how can i do that. my i use to make a request like below using api.js
api
.post('api_end_point',parameters,headers)
.then(response=>{
})
.catch(error =>{
})
thanks
It means that there is some issue with your AsyncStorage.getItem(SECURE_KEY) ,probably it's not a proper json object.do a console.log of AsyncStorage.getItem(SECURE_KEY) and see what value you get.

Axios may ignore default headers

I'm using axios in my nuxt project.
When I make a request by setting headers config in the request config, the default headers are ignored on node.js.
When I run the following code on node.js
import axios from "axios";
axios.defaults.headers.common["default-header"] = "default-header";
axios.get("https://jsonplaceholder.typicode.com/todos/1", {
headers: { header1: "header1" },
})
.then((response) => {
console.error(response.config);
});
The response config headers is as follows
headers: {
header1: 'header1'
}
The expected response config headers is as follows
headers: {
default-header: "default-header"
header1: "header1"
}
When I run the following code on browser (like Chrome), response config headers is as expected.
Is this a bug in axios?
I created a repository for verification
https://github.com/mimi6612/nuxt-axios-request-config-sample
I think you are missing the axios.create methode.
import axios from 'axios'
const requestHandler = config => {
config.headers = {
'defaultHeader': 'myDefaultHeaderString'
}
config.crossDomain = true
return config
}
const requester = axios.create()
requester.interceptors.request.use(requestHandler)
export requester

Put API KEY in axios

I just started learn React but I have problem when I trying to make a request to the CoinMarketCap API with axios and tried several ways to set my API key. I have also also tried on Postman but message appears API key missing.
export const apiBaseURL = 'https://pro.coinmarketcap.com';
Tried like this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`,
{ headers =
{ 'X-CMC_PRO_API_KEY': 'apicode', }
})
this
dispatch({ type: FETCHING_COIN_DATA })
let config = { 'X-CMC_PRO_API_KEY': 'apicode' };
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`, { headers: config })
and this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?X-CMC_PRO_API_KEY=apicode`)
Thank you
The short answer to adding an X-Api-Key to an http request with axios can be summed up with the following example:
const url =
"https://someweirdawssubdomain.execute-api.us-east-9.amazonaws.com/prod/custom-endpoint";
const config = {
headers: {
"Content-Type": "application/json",
},
};
// Add Your Key Here!!!
axios.defaults.headers.common = {
"X-API-Key": "******this_is_a_secret_api_key**********",
};
const smsD = await axios({
method: "post",
url: url,
data: {
message: "Some message to a lonely_server",
},
config,
});
Adding the key to the default headers was the only way I could get this to work.
Use CMC_PRO_API_KEY as a query parameter, instead of X-CMC_PRO_API_KEY:
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?CMC_PRO_API_KEY=apicode`)
I realize this has been solved; for the sake of alternatives here is how I did it. I created a instance of axios in /includes/axios:
import axios from "axios";
const instance = axios.create({
baseURL: "https://example.com/api",
headers: {
"Content-Type": "application/json",
"x-api-key": "****API_KEY_HERE****",
},
});
export default instance;
Now axios can be imported anywhere in the project with the give configuration. Ideally you want to add your secret to the ENV variable for security reasons.

How can access $auth.getToken('local') in a service?

I am new in nuxtjs.i am trying to create a service like EventService.js.From EventService.js i want to get data using axios. but i want to set Authorization header.But can't get the access token from $auth.getToken('local'). i don't want to set Authorization header every axios request.Thanks
import axios from 'axios'
const apiClient = axios.create({
baseURL: `example.com`,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
'Authorization': "Bearer " + **$auth.getToken('local')**
}
})
export default {
getEvents() {
return apiClient.get('/events')
}
}
axios interceptors solved my problem
apiClient.interceptors.request.use(
(config) => {config.headers["Authorization"] =cookies.get("auth._token.local")
.replace(/%/g, " ")
return config
},
function(error) {
return Promise.reject(error) })
You can import 'axios' in your main.js (entry file) and add the following:
import axios from 'axios'
axios.defaults.headers.common['Authorization'] = `Bearer ${localstorage.getItem('token')}`;
And when you setup your token for the first time, your can set it up on the localstorage and assign again to the axios defaults headers:
import axios from 'axios'
const token = <AUTH_TOKEN>
// when setting the token
localstorage.setItem('token', token)
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
This will be enough to send the Authorization header in every axios request you make.