How to configure API URL running on localhost on port 8080 in nuxt js? - rest

I have the following vue file. My REST API base URL is http://localhost:8080/api/. When I access http://localhost:8080/api/dfc/system/docbases directly, I get the response as shown.
["gr_swy","SubWayX_DEMO"]
But I want to get the response through nuxt js which is running on http://localhost:3000/restapi/. I tried to follow all the articles, but not able to figure out where I'm doing wrong.
<template>
<div class="container">
{{docbases}}
</div>
</template>
<script>
import axios from "axios";
#import axios from "../../.nuxt/axios"; (tried both)
export default {
methods: {
// asyncData({ req, params }) {
// return axios.get("http://localhost:8080/api/dfc/system/docbases")
// .then(res => {
// return { docbases: res.data };
// }).catch((e) => {
// error({ statusCode: 404, message: 'Not found' })
// })
// },
async asyncData ({ params }) {
const { data } = await axios.get('http://localhost:8080/api/dfc/system/docbases');
return { docbases: data }
}
},
head: {
title: "D2Rest"
}
};
</script>
My nuxt.config.js is like this: I tried changeOrigin with true and false both. Can you please help me what extra things I need to configure?
axios: {
proxy: true,
},
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
},
proxy: {
'/api/': {
target: 'http://localhost:8080/',
pathRewrite: { "^/api": "" },
changeOrigin: false,
prependPath: false
}
},

Based on your configuration, I'm assuming you're using the Nuxt Axios module...
The problem seems to be that you're importing Axios unnecessarily, thus bypassing your axios configuration in nuxt.config.js. The Nuxt Axios module docs describe its usage in components:
export default {
async asyncData({ $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
return { ip }
}
}
Note the destructured parameter $axios. Use that parameter instead of importing your own instance of axios (i.e., don't do import axios from 'axios'), which is not the same as the one configured by Nuxt. No other imports are needed for $axios.
Proxy URL
Another problem is that your explicitly requesting the proxy address in the URL, but that should be excluded:
// const { data } = await $axios.get('http://localhost:8080/api/dfc/system/docbases'); // DON'T DO THIS
const { data } = await $axios.get('/api/dfc/system/docbases');

Sorry, I didn't enable Cross Origin in my java code. I have enabled now and it's resolved.
#CrossOrigin(origins = "http://localhost:3000")

Related

sending request through proxy. request library works, axios does not

I am trying to update some old code to get rid of the request package since it is no longer maintained. I attempted to replace a proxy request with axios, but it doesn't work (I just get a timeout). Am I missing an axios config somewhere? The example using the request package works fine.
FAILS
export function sendAxiosApiRequest(enableProxy, proxyIndex,url,filepath?:string):object {
//https://support.zyte.com/support/discussions/topics/22000014602
let ca='READ IN FILE HERE'
let getOptions = {
url: url,
httpsAgent: tunnel.httpsOverHttp({
ca: ca,
proxy: {
host: 'http://MY_API_KEY:#proxy.crawlera.com',
port: '8011',
},
}),
proxy: false, //disable auto config, bc we set it manually
} as any;
console.log({getOptions})
return new Promise(resolve => {
try {
axios.get(getOptions,(err,response,html)=>{
if(err){
console.log(err);
resolve(false);
}
else {
try{
const output = JSON.parse(html);
resolve(output);
}catch(e){
console.log({html})
throw `ERROR parsing html: `+JSON.stringify(e)
}
}
})
}
catch (e) {
console.log(`Err parsing result from sendApiRequest:`,e);
resolve(false);
}
})
}
WORKS
export function sendRequestApiRequest(enableProxy, proxyIndex,url,filepath?:string):object {
let ca='READ IN FILE HERE'
let getOptions = {
url: url,
jar: true,
followAllRedirects: false,
} as any;
//console.log({filepath})
getOptions.proxy= 'http://MY_API_KEY:#proxy.crawlera.com'
getOptions.ca=ca
getOptions.requestCert =true
getOptions.rejectUnauthorized= true
return new Promise(resolve => {
try {
request.get(getOptions,(err,response,html)=>{
if(err){
console.log(err);
resolve(false);
}
else {
const output = JSON.parse(html);
resolve(output);
}
})
}
catch (e) {
console.log(e);
resolve(false);
}
})
}
Please have a look at the axios docs.
The method signature for the get-requests is axios.get(url[, config]) but your first parameter is actually an object. You might want to use axios({}) and update your getOptions with the missing method key:
let getOptions = {
url: url,
method: 'get', // this was missing!
httpsAgent: tunnel.httpsOverHttp({
ca: ca,
proxy: {
host: 'MY_API_KEY:#proxy.crawlera.com', // http is not needed, but it was http but you use httpsAgent?!
port: 8011,
},
}),
proxy: false,
} as any;

how to use env variables in nuxt 3 outside of setup scripts

So the problem is that I would like to use Axios instance. Because:
new useFetch is only possible to use inside of components aka setup scrips. https://v3.nuxtjs.org/guide/features/data-fetching/
community axios module is only possible inside of nuxt2 https://github.com/nuxt-community/axios-module/issues/536 and are nor supported in nuxt3
I need to make calls in pinia actions(store) to my backend service.
nuxt.config.js
import { defineNuxtConfig } from "nuxt";
export default defineNuxtConfig({
runtimeConfig: {
public: {
apiBase: process.env.API_BASE_URL ?? "http://localhost:8080/api/v1",
},
},
env: {
apiBase: process.env.API_BASE_URL ?? "http://localhost:8080/api/v1",
},
buildModules: ["#pinia/nuxt"],
});
and here is instance.js
import axios, { AxiosResponse } from "axios";
const instance = axios.create({
baseURL: process.env.API_BASE_URL,
});
instance.interceptors.response.use((response: AxiosResponse) => {
return response.data;
});
export default instance;
So it does see the envs on server-side as I can console log them but on client I do receive can't read of undefined
You can access your env variables using a composable and the useRuntimeConfig method.
Something like this for instance:
// file composables/use-axios-instance.ts
import axios, { AxiosResponse } from "axios";
let instance = null;
export const useAxiosInstance = () => {
const { API_BASE_URL } = useRuntimeConfig();
if (!instance) {
instance = axios.create({
baseURL: API_BASE_URL,
});
instance.interceptors.response.use((response: AxiosResponse) => {
return response.data;
});
}
return instance;
};
Then you can access to your axios instance using const axios = useAxiosInstance();

My POST request works on Postman but not with axios

I have a nuxt project deployed on Netlify and now I want to add a newsletter (add a subscriber to my audience on Mailchimp). To achieve that, I've opted to use the AWS serverless lambda functions. To be honest, it's the first time that i've heard about serverless functions. I found this tutorial https://hashinteractive.com/blog/nuxt-js-mailchimp-integration-add-contact-to-list/ and at the end, i've decided to make a test on Postman. I've made a post to http://localhost:8888/.netlify/functions/subscribe and it worked. But when I try the same thing with axios I get the error 405 (method not allowed).
Newsletter.vue
<form #submit.prevent='submitNewsletter' class="newsletter__form" >
<input type="email" placeholder="E-mail" class="newsletter__form-input" v-model="email">
<button class="newsletter__form-button" type="submit">Subscribe</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data(){
return{
email: ''
}
},
methods:{
submitNewsletter(){
axios.post('http://localhost:8888/.netlify/functions/subscribe', { email: this.email}, {
headers: {
methods: 'POST',
'Content-Type':'application/json'
}
})
.then(function (response) {
console.log(response);
}).
catch((error) =>{
console.log('The error:' + error)
})
this.$toasted.success("Thank you for your subscription !!!", {
theme: "toasted-primary",
position: "top-left",
containerClass: 'myContainer',
fitToScreen: true,
fullWidth: true,
duration : 5000
});
}
}
}
</script>
functions > subscribe > subscribe.js
const fetch = require('node-fetch');
const base64 = require('base-64');
exports.handler = async (event, context) => {
// Only allow POST
if (event.httpMethod !== 'POST') {
return { statusCode: 405, body: 'Method Not Allowed' };
}
const errorGen = msg => {
return { statusCode: 500, body: msg };
};
try {
const { email } = JSON.parse(event.body);
console.log(email);
if (!email) {
return errorGen('Missing Email');
}
const subscriber = {
email_address: email,
status: 'subscribed',
};
console.log(subscriber);
console.log(JSON.stringify(subscriber));
const creds = `blooming-thoughts:${process.env.MAILCHIMPS_API_KEY}`;
const response = await fetch(`https://us20.api.mailchimp.com/3.0/lists/${process.env.AUDIENCE_ID}/members/`, {
method: 'POST',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: `Basic ${base64.encode(creds)}`, },
body: JSON.stringify(subscriber),
});
const data = await response.json();
if (!response.ok) {
// NOT res.status >= 200 && res.status < 300
return { statusCode: data.status, body: data.detail };
}
return {
statusCode: 200,
body: JSON.stringify({ msg: "You've signed up to the mailing list!", detail: data, }),
};
} catch (err) {
console.log(err); // output to netlify function log
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }),
};
}
};
My netlify.toml
[build]
publish = "dist"
functions = 'functions'
I've made a push to my repository and netlify built without any error, but when I try to add a newsletter from my site nothing happens.
I've solved my problem. If you're having trouble like I was, follow these steps:
Create a folder called functions in your root directory, then create a index.js (the file name is up to you).
Create a file called netlify.toml and add the following code :
[build]
functions = "functions"
Then, inside your index.js goes the code that will communicate with your API
On the vue component, make a post request to the <your-site>/.netlify/functions/index . You can find the endpoint going to functions on netlify dashbord.
Don't forget to register your env variables on Netlify (Build & Deploy) and that's it.

Wuxt.js (Nuxt.js) getting out data from axios response

I want to fetch out menu items from the Wordpress json response with Wuxt framework (Nuxt + Wordpress), but I can't access the data object outside the fetch (error message is that data is not defined)
This is my code
<script>
import axios from 'axios'
import Logo from '~/components/Logo'
export default {
components: {
Logo
},
async fetch ({ params, error }) {
try {
let { data } = await axios.get('http://localhost:3080/wp-json/wuxt/v1/menu')
return data
} catch (e) {
error({ message: 'Not found', statusCode: 404 })
}
}
}
</script>
How can the data object be accessed, for inserting into the template?
If you are using fetch than all your data should be commiting into store, and accessed from it. If you want to return data, use asyncData method.
I had to change the code a bit, that it returns a data function with variable, so it looks like this.
export default {
components: {
Logo
},
data() {
return { menus: [] }
},
mounted() {
fetch('http://localhost:3080/wp-json/wuxt/v1/menu')
.then(response => {
response.json().then(menus => {
this.menus = menus;
})
})
}
}

make REST call with typescript

I installed the "sb admin 2" dashboard with html5/angular2.
This sample works with typescript. To instanciate charts, the file charts.compenent.ts defines the class and then defines the charts attributes and data as follows
import { Component, OnInit} from '#angular/core';
#Component({
moduleId: module.id,
selector: 'chart-cmp',
templateUrl: 'chart.component.html'
})
export class ChartComponent implements OnInit {
ngOnInit() {
var container:any = $('#container');
container.highcharts({
chart: {
type: 'area'
},
...................................
In my case, I want to get the date from a restfull service.
Can you help me to do this please??
any input will help
Make sure you have the correct imports,
import {Http, Response, URLSearchParams} from '#angular/http';
This is how to make a get request,
Get Request
saveProfile(model: Profile, isValid: boolean) {
let params: URLSearchParams = new URLSearchParams();
// set params to go to URL
params.set('email', model.email);
params.set('first_name', model.first_name);
return this.http.get('url/path/here/dont/forget/port',
{ search: params })
.map((res: Response) => res.json())
.subscribe((res) => {
console.log(res);
// Map the values in the response to useable variables
this.auth.user.email = res.user.email;
this.auth.user.first_name = res.user.first_name;
});
}
}
Post Request
How to make a post request,This is a popular post request used in the auth0 library. You can find that here
authenticate(username, password) {
let creds = JSON.stringify({ username: username.value, password: password.value });
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:3001/sessions/create', creds, {
headers: headers
})
.subscribe(
data => {
this.saveJwt(data.json().id_token);
username.value = null;
password.value = null;
},
err => this.logError(err.json().message),
() => console.log('Authentication Complete')
);
}
These examples will get a response from the server. If you want to do some more technical things like get the new data to update in the view, you will have to create an observable. If I were you I would get this down then when you need to understand observable you can incorporate that.