I decided to rewrite my application from spa vue to nuxt but i faced a problem in spa, in vue i could just import store and used it but in nuxt i cant do the same, i am getting undefined object every time
in vue spa i had folder with some api services and with main api.js which include this code
import axios from 'axios'
import store from '#/store/index'
export default () => {
return axios.create({
baseURL: `http://myip.com/`,
headers: {
Authorization: `Bearer ${store.state.token}`
}
})
}
then in other js files i just import this api.js file and use something like this
import Api from '#/services/Api'
export default {
register (credetinals){
return Api().post('register', credetinals)
},
login (credetinals){
return Api().post('login', credetinals)
}
}
so i had 10 js files services where i include api.js and then in files *.vue i just import this service
how can i do the same in nuxt ?
If you add your state under the /store/index.js it will automatically append in the application, you dont need to import it in your file.
What you can do is try to check the state using:
window.$nuxt.$store.state
Also dont forget to add a condition process.browser since you want to check it in browser.
Here is what I did in my api.js file for your reference:
// Libraries
import axios from 'axios';
// API Instance
export const instance = axios.create({
baseURL: 'http://myip.com/',
headers: {},
validateStatus: status => {
return status;
},
});
// API Interceptors
instance.interceptors.request.use(config => {
if (process.browser) {
const userToken = window.$nuxt.$store.getters.getUserToken;
// Set Authorization token
if (userToken) {
config.headers['Authorization'] = `Bearer ${userToken}`;
}
}
return config;
}, function (error) {
return Promise.reject(error);
});
Related
I have this directory structure:
- pages
- api
- products
- pro
- [id].js
- add.js
[id].js
import { upload, baseHandler } from 'helpers';
import { sequelize } from 'lib';
import { init, Suppliers, Products} from 'models';
import { supplierController, productController } from 'controllers';
const handler = baseHandler.get( async (req, res) => {
const {
query: { id, name },
method,
} = req
init()
res.status(400).json(id)
})
export default handler;
export const config = {
api: {
bodyParser: false,
},
};
The static routes works fine but not the dynamic ones. I get this error when I try to access them
error - Error: getaddrinfo ENOTFOUND api.example.com
which means Next.js does not add dynamic routes from the file system.
Im using NestJS via HTTPS.
import { NestFactory } from '#nestjs/core';
import { fstat } from 'fs';
import { AppModule } from './app.module';
import {readFileSync} from 'fs'
async function bootstrap() {
const httpsOptions = {
key:readFileSync('tsl/private-key.pem'),
cert:readFileSync('tsl/public-cert.pem')
}
const app = await NestFactory.create(AppModule,{httpsOptions});
await app.listen(3000);
}
bootstrap();
I try to get simple POST request:
#Post()
test(#Body() body){
console.log(body);
}
But output is always {}
POSTMAN:
I readed that nestjs cant parse data correctly. How can i fix that?
Your postman request needs to be set to raw and JSON, not raw and Text
Integrate swagger into your application.
It is an open API and supported by nestjs.
https://docs.nestjs.com/openapi/introduction
New to Axios and Node as a backend- have inherited some code in React for a login page and am trying to figure out why I can't make a POST to the backend.
This is my .env file:
REACT_APP_BACKEND_URL=http://localhost:3000/admin
And there is a file called API.js
import axios from "axios";
// Set config defaults when creating the instance
export const CompanyAPI = () => {
let api = axios.create({
baseURL: process.env.REACT_APP_BACKEND_URL,
timeout: 10000,
headers: {
"Content-Type": "application/json",
},
});
return api;
};
And then there is a LoginPage.js:
export const LoginPage = () => {
const API = CompanyAPI();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const getAuth = (e) => {
e.preventDefault();
API.post("/auth/login", {
email: email,
password: password,
})
.then(async (response) => {
if (response.status === 200) {
await localStorage.setItem("jwt_key_admin", response.data.token);
setTokenKey(response.data.token);
setIsAuth(true);
navigate("/");
}
})
.catch((error) =>
alert(
"Login Failed"
)
);
};
My question is, is there an example on how I could use express to handle the /auth/login endpoint and complement the existing API.js file?
Basically what I see from this code is:
An axios instance was created and the baseURL was set to being http://localhost:3000/admin
From first glance I can tell that all Api calls that you make a resulting to 404 reason being React locally will always run on port 3000 unless that port is in use.
So now your axios baseURL being to set to port 3000 definitely axios should return a 404 because you surely do not have the endpoint that you are trying to hit
Solution:
Here you are to change the baseURL's port number to the port where Nodejs server is listening on
Then once that is said and done then make sure that even the endpoints that you are trying to hit do exist then your axios calls should work now
Advise:
If the Axios instance created is confusing drop it for a bit and import raw axios not the instance then use axios in it's basic form then once you have that working you surely will have established the correct port number and everything then you can edit the axios instance created with baseURL you have established.
Add
"proxy":"http://localhost:3000/admin"
in your package.json file and restart your React App.
I am very new to typescript/javascript, I am trying to build backend rest apis with session
following is app.ts file
import express from "express";
import { applyMiddleware, applyRoutes } from "./utils";
import routes from "./services";
const app = express();
var ses= {
secret: "secret_session",
resave: true,
saveUninitialized: true,
cookie: { maxAge: 3600000,secure: false, httpOnly: true
}
if (app.get('env') === 'production') {
app.set('trust proxy', 1)
ses.cookie.secure = true
}
app.use(session(ses));
applyRoutes(routes, app);
I have started the server and applied the middlewares for error handling but those are not related to question in my opinion so I'm not adding code for it. Following is my routes.ts code where I'm trying to set the session.
import { Request, Response } from "express";
import { getAll, getByKeyword, addNewProduct } from "./productControllers";
{
path: "/api/v1/getAllProducts",
method: "get",
handler: [
(req: Request, res: Response) => {
getAll()
.then((row: any) => {
var sess = req.session;
sess.views = 1;
res.status(200).json({ data: row });
})
.catch(err => {
res.json({
message: err
});
});
}
]
}
I'm getting error at sess.views = 1;
I have tried the suggested questions before asking it, none of them were of any help to me.
EDIT:
I have created an index.ts
import searchRoutes from "./products/routes";
export default [...searchRoutes];
I have another util class
export const applyRoutes = (routes: Route[], router: Router) => {
for (const route of routes) {
const { method, path, handler } = route;
(router as any)[method](path, handler);
}
}
You are using an interface which is Request for express.js. But it doesn't have type definition for session. So typescript throws a compile error. To solve it you need to define session type under Request interface.
You could define a session.d.ts file under your project. And create required types & interfaces. Like:
declare global {
namespace Express {
interface Request {
session?: Session;
sessionID?: string;
}
}
}
interface Session{
mySessionVarible:string
}
But the good thing is we have DefinitilyTyped project which you can find many type definitions. This needs to solve your compile problem.
npm install --save-dev #types/express-session
And don't forget to change your import for Request.
import { Request, Response } from "#types/express-session";
I am getting error 401 or CORS related error when fetching the [Active Directory plugin through its own plugin for React (React-ADAL).
I have to integrate the Active Directory Web API plugin with my React.js App to be able to fetch data from my Microsoft Dynamics 365 CRM platform.
According to Micosoft documentation the ADAL plugin facilitates this CORS stuff but I still see this CORS error while fetching with adalApiFetch() function.
This is my adalConfig.js file:
import { AuthenticationContext, adalFetch, withAdalLogin } from 'react-adal';
export const adalConfig = {
tenant: '<tenant id>',
clientId: '<active directory app id>',
endpoints: {
api: '<active directory app id>'
},
cacheLocation: 'localStorage',
};
export const authContext = new AuthenticationContext(adalConfig);
export const adalApiFetch = (fetch, url, options) => adalFetch(authContext, adalConfig.endpoints.api, fetch, url, options);
export const withAdalLoginApi = withAdalLogin(authContext, adalConfig.endpoints.api);
And then my Component code to fetch with the plugin:
import React, { Component } from 'react';
import { adalApiFetch } from '../../../adalConfig';
export default class AComponent extends Component {
componentDidMount() {
this.getLeads();
}
getLeads() {
let result;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
const options = {
method: 'GET',
headers
};
adalApiFetch(fetch, 'https://myorg.crm2.dynamics.com/api/data/v9.1/leads', options)
.then(response =>{
console.log(response);
})
.catch(error => console.error('SERVER ERROR:', error));
}
}
My Chrome's developer tools displays:
Any ideas to fix this? Thanks in advance.