I have a front-end built in React and Backend built in Nodejs (framework Adonisjs). I want to share some code between The Client and the Server. My Team can't use NPM or GitHub to do it, because of Company Policies.
Reading NPM docs, I found a possible solution:
On package.json I included the following line in "dependencies" entry:
"sharedCodeModule": "index.js:../<sharedCodeFolder>"
Doing that, I could import the module in both Front and Backend. The thing is that I've never seen such solution for this problem (not that I searched a lot). Anyone can see any problems in this approach?
Ps: Sorry for bad English. Not a native speaker.
Not sure I understand the question, yet, if your backend is perfectly set to make post and get requests, your front end should only take call your backend funcionalities.
Try to use npm axios , and you can have a example.js file like:
import axios from 'axios';
export default axios.create({
baseURL: 'http://127.0.0.1:8000/'
})
where you switch that baseURL for what you actually need. And then on your frontend you should have axios post and get requests, for example, you either import the above file in the file of the frontend component and do the post/get like:
import axiosFunc from "./example";
class WhateverComp extends Component {
constructor(props) {
super(props);
this.state = {
(...)
};
}
(...)
handleSubmit = async () => {
const response = await axiosFunc.post("/yourEndPointHere", {
exampleParam: this.state.param
});
message.success("success.");
};
(...)
Or, as you can see in the link I gave you, with axios, you make call it directly and do your requests like the example below:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Again, I'm not sure I understood what you actually want to do, I hope axios helps you.
Related
I am new to Nest JS Framework and I dont whether I can use json-server to mock external API.
I have already checked NestJS documentation but its not having any example.
I found one question on Stack-overflow but it not complete Example Json-server mocking API instead of calls
I simply want to make one POST call and 1 GET Call.
Dont know which file I write these mocked POST and GET calls.
My first question is, what is your purpose for using NestJS?
You can think of NestJS and json-server as "similar" in their goal; you would use one OR the other. Not both.
If your goal is just to mock data and server, then you have everything you need with json-server. You wouldn't need NestJS.
If what you are looking for is to mock data to retrieve instead of creating a database, you can simply create a simple object in NestJS and retrieve data from there.
For the latter, it might look something like this (not tested):
// app.controller.ts
import { Controller, Get } from '#nestjs/common';
import { AppService } from '../services/app.service';
#Controller('api')
export class AppController {
constructor(private readonly appService: AppService) {}
#Get('/users')
findAllUsers(): Promise<any> {
return this.appService.findAllUsers();
}
}
// app.service.ts
import { Injectable } from '#nestjs/common';
#Injectable()
export class AppService {
private getMockData() {
return {
users: [
{
name: 'john',
email: 'john#doe.com',
},
{
name: 'jane',
email: 'jane#doe.com',
},
],
};
}
findAllUsers(): Promise<any> {
return new Promise(function (resolve, reject) {
const data = this.getMockData();
if (data.users.length > 0) resolve(data.users);
else reject('No users found');
});
}
}
Now you would just have to do the request GET <host>/api/users where the host will be something like http://localhost:8080 in your local machine.
Right now I have React app initialized with Vite connected with Sanity.
Everything is working just fine, Sanity client is connected, React is fetching data from Sanity, I'm receiving it with no problem.
But the problem is, that if I deploy React app with Sanity connected, then I will leak my projectID and sanity_token to the fronted, which I want to avoid of course.
So I have to make some backend REST API which will be fetched by React, and then my API will fetch Sanity. I could do it with Node.js and Express without problem, but I decided that I will use NestJS and learn something instead.
But when it comes to NestJS, everything is connected a bit different.
On the front I had :
import sanityClient from '#sanity/client';
export const client = sanityClient({
projectId: import.meta.env.VITE_SANITY_PROJECT_ID,
dataset: 'production',
apiVersion: '2022-02-01',
useCdn: true,
token: import.meta.env.VITE_SANITY_TOKEN
});
And for NestJS I found something like this:
import { Injectable } from '#nestjs/common';
import sanityClient, { SanityClient } from '#sanity/client';
#Injectable()
export class SanityService {
public readonly client: SanityClient = sanityClient({
projectId: process.env.SANITY_PROJECT_ID,
dataset: 'production',
apiVersion: '2022-02-01',
useCdn: true,
token: process.env.SANITY_TOKEN
});
}
My question is that if it's a good way to connect Sanity client?
How to query Sanity client with specified GROQ query?
Till now I was using this on the frontend, but it's not gonna work in NestJS:
const query = '*[_type == "blogPost"]';
client.fetch(query)
.then((data) => {
setPosts(data);
})
.catch((err) => {
console.log(err);
})
It turned out that this is the proper way to connect with Sanity client, I had an issue with that similar to this thread
And the solution was the same as in the thread above. Add "esModuleInterop": true to tsconfig.json.
{
"compilerOptions": {
...
"esModuleInterop": true,
...
}
}
Then call for data to sanity client is working properly:
#Get()
async getAllPosts() {
// initialize sanity instance
const sanityService = new SanityService();
// your query
const query = '*[_type == "blogPost"]';
try {
const data = await sanityService.client.fetch(query);
return data;
} catch (error) {
console.log(error.msg);
}
}
I have already created a backend api with node and express which works great, through Postman and Insomnia, but for some reason my create function wont post to my api. It can login to the API fine, and the form is returned with each user inputted field, but the issue relates to somewhere after axios.post, as if i put in the incorrect url it throws a 404, but if i put in the correct url it doesnt throw any error but completely skips over the .then(response function and goes straight to console.log(3). Any ideas or help relating to this would be great, Thanks!
Imports
import {useState} from 'react'
import axios from 'axios'
import {TextField, MenuItem, FormControl, Select, InputLabel, Button, Checkbox} from '#mui/material'
import { useNavigate } from 'react-router-dom'
Submit form code
const submitForm = () => {
console.log(form)
let token = localStorage.getItem('token')
console.log(1)
axios.post('http://localhost:9000/miniatures/create', form,{
headers: {
"Content-Type": "application/json",
"Authorization": `jwt ${token}`
}
})
.then(response => {
console.log(2)
console.log(response.data)
navigate(`/miniatures/${response.data._id}`)
})
.catch(err => console.log(err))
console.log(3)
}
React likely does not know how to proxy API requests to the Express server.
In package.json for the front end, try adding:
"proxy": "http://localhost:9000",
Then, make your post request to (something like) axios.post(/miniatures/create). The exact path will depend on how you structured your Express routes. It could be something like /api/miniatures/create.
In development, the development server will recognize that it’s not a
static asset, and will proxy your request.
I am creating a GraphQL app using Next.js for server side rendering. As you might know, there is a recommended way to implement clean URL using Express. I am trying to achieve the same using graphql-yoga but it's not working.
I have tried server.express.get('/route', ...) and server.get('/route', ...) but nothing is working. In the documentation they have given server.express.get(server.options.endpoint, handler()) but it's not working for me.
Has anyone ever implemented clean Next.js URL in a GraphQL Yoga server, and how did you achieve it? Below is how I am creating the server.
function createServer() {
return new GraphQLServer({
typeDefs: "src/schema.graphql",
resolvers: {
Mutation,
Query
},
context: req => ({ ...req, db })
});
}
const server = createServer();
server.express.post('/product/name', (req,res,next) => {
//this is where i want to implement next clean url
//but it's not working
console.log('Am never reached..');
next();
})
With the new versions of Next.js, creating clean URL is straightforward.
Create a parameterised page (e.g. pages/post/[pid].js):
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
return <p>Post: {pid}</p>
}
export default Post
More info in the Next.js documentation regarding dynamic routes.
You can then link to it and show the desired URL:
<Link href="/post/[pid]" as="/post/abc">
<a>First Post</a>
</Link>
I am building a web app using vue/webpack for the front end and node.js/express on back end. The node.js back end is exposing REST APIs that are used by the front end to login, logout and other CRUD-like operations.
On server side, the login REST API is setting a JWT token and redirects to the vue application home path.
On front end side, the vue components access (including home) is guarded by the beforeEach method of the vue router (based on sample from here).
My question is, from within my vue application, how can I access the JWT token (set by the login REST API in the HTTP Headers of the response) and store it in my vuex store so that my vue components can use it?
Thanks for your help!
PS: I am using node.js 8.5, Vue 2.4.4, Vue Router 2.7, Vuex 2.4.1
Use Axios Interceptors:
import { defaults, get } from 'lodash';
import axios from 'axios';
import store from 'vuex-store';
import def from './default';
export const connection = (options = {}) => {
def.headers = { Authorization: store.getters.auth.getToken() };
const instance = axios.create(defaults(def, options));
instance.interceptors.response.use(
function (response) {
const newtoken = get(response, 'headers.authorization');
if (newtoken) store.dispatch('setToken', newtoken);
console.log(response.data);
return response;
},
function (error) {
switch (error.response.status) {
case 401:
store.dispatch('logoff');
break;
default:
console.log(error.response);
}
return Promise.reject(error);
}
);
return instance;
};