Send data between GraphQL Node.js server and React in Nx - javascript

I setup two projects, Node.js and React in Nx monorepo. I would like to use GraphQL for communication. Projects I'm running with command nx serve api(Node.js) and nx serve totodile (React). Problem is that React cannot access data from /graphql endpoint.
React is running on http://localhost:4200/.
Node.js is running on http://localhost:3333/.
Node.js part
According to GraphQL instructions for Node.js I run Node.js server. I have created two endpoints /api and /graphql.
import * as express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { Message } from '#totodile/api-interfaces';
import { buildSchema } from 'graphql';
const app = express();
const greeting: Message = { message: 'Welcome to api!' };
app.get('/api', (req, res) => {
res.send(greeting);
});
app.use('/graphql', graphqlHTTP({
schema: buildSchema(`
type Query {
hello : String
}
`),
rootValue: {
hello: () => 'Hello world'
},
graphiql: true,
}));
const port = process.env.port || 3333;
const server = app.listen(port, () => {
console.log('Listening at http://localhost:' + port + '/api');
});
server.on('error', console.error);
In a result I am able to connect to http://localhost:3333/graphql and receive response. So graphql server is working well.
// graphql response
{
"data": {
"hello": "Hello world"
}
}
React part
Inside functional component I fetch with /api and /graphql. First one return valid data, but /graphql is returning 404, Cannot POST /graphql.
useEffect(() => {
fetch('/api') // successfully return data
.then((r) => r.json())
.then(setMessage);
fetch('/graphql', { // 404, no data
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({query: "{ hello }"})
})
.then(r => r.json())
.then(data => console.log('data returned:', data));
}, []);
I investigate that:
http://localhost:4200/api return valid data ("message": "Welcome to api!")
http://localhost:3333/api return valid data ("message": "Welcome to api!")
http://localhost:4200/graphql 404 no data
http://localhost:3333/graphql return valid data ("hello": "Hello world")
It must be something with ports.
I don't understand how /api is able to return any data. Why on both ports?
What should I do to share data from /graphql to react?

To fix issue there was 2 steps to do:
In React I should fetch from endpoint with port fetch('http://localhost:3333/graphql',(...))
In Node.js there is need to use cors library
import express from "express";
import cors from 'cors';
const app = express();
app.use(cors());
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
...

Related

i try to upload file in my mocha nodejs test but i got [Object null prototype] { file: { ... }}

i find evrywhere solution white :
app.use(bodyParser.urlencoded({extended: true}));
i can use
JSON.stringify(req.files)
but im sur having a way to fix my problem
my mocha test :
it('a file', async function () {
const body = { pseudo: 'user', password: 'test#123', mail: 'supermail' };
const response = await fetch(hostName + '/authentication/register', {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' }
})
const usr = await response.json();
request.post('/usrAction1/doc')
.field('token', usr.token)
.attach('file', 'test/test.pdf')
.end(function (err, res) {
if (err) {
console.log(err)
}
console.log(res.status) // 'success' status
});
});
and my rout handler :
router.post('/doc', async (req, res) => {
console.log('req.files');
console.log(req.files)
})
also my server.js:
import express from 'express'
import authentication from './src/login.js'
import './global/host.js'
import bodyParser from 'body-parser'
import cors from "cors"
import verifyToken from './middleware/auth.js'
import { userAction1, userAction2 } from './src/userAction.js'
import verifyLevel from './middleware/level.js'
import fileUpload from 'express-fileupload';
export default function myApp() {
const whitelist = [/http:\/\/localhost:*/, /http:\/\/127.0.0.1:*/]
const corsConfig = { origin: whitelist }
const app = express();
const port = hostPort;
//json encoded
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors(corsConfig))
// enable files upload
app.use(fileUpload({
createParentPath: true
}));
app.use('/usrAction1', userAction1())
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
return app;
}
myApp();
but don't to work for me .
i also test white external client server who juste runing a form and send it to my tested adress and
do the same [Object null prototype]
thank u for evry litel help
i waiting of some help i using this magique code i found somwhere on stackoverflow:
req.files && Object.keys(req.files)?.map((obj, idx) => { console.log(req.files['file'].data) })
if somone have a better idea i waiting .
thank to all

how to get cookie in react passed from express js api (MERN stack)

I have an api in express js that stores token in cookie on the client-side (react). The cookie is generated only when the user logins into the site. For example, when I test the login api with the postman, the cookie is generated as expected like this:
But when I log in with react.js then no cookie is found in the browser. Looks like the cookie was not passed to the front end as the screenshot demonstrates below:
As we got an alert message this means express api is working perfectly without any error!!
Here is my index.js file on express js that includes cookie-parser middleware as well
require("dotenv").config();
const port = process.env.PORT || 5050;
const express = require("express");
const app = express();
const cors = require("cors");
const authRouter = require("./routes/auth");
var cookieParser = require('cookie-parser')
connect_db();
app.use(express.json());
app.use(cookieParser())
app.use(cors());
app.use("/" , authRouter);
app.listen(port , () => {
console.log("Server is running!!");
})
Code for setting up the cookie from express api only controller
const User = require("../models/user");
const jwt = require("jsonwebtoken");
const bcrypt = require('bcrypt')
const login = async (req, res) => {
const { email, password } = req.body;
try {
const checkDetails = await User.findOne({ email });
if (checkDetails) {
const { password: hashedPassword, token, username } = checkDetails;
bcrypt.compare(password, hashedPassword, function (err, matched) {
if (matched) {
res.cookie("token", token, { expires: new Date(Date.now() + (5 * 60000)) , httpOnly: true }).json({ "message": "You logged in sucessfully!" });
} else {
res.status(500).json({ "message": "Wrong password" });
}
});
} else {
res.status(500).json({ "message": "Wrong email" });
}
} catch (error) {
console.log(error.message);
}
}
Here is the react.js code that I am using to fetch data from api without using a proxy in package.json file
if (errors.length === 0) {
const isLogin = await fetch("http://localhost:5000/api/login", {
method: "POST",
body: JSON.stringify({ email, password }),
headers: {
"Content-Type": "application/json"
}
});
const res = await isLogin.json();
if(res) alert(res.message);
}
I want to get to know what is the reason behind this "getting cookie in postman but not in the browser". Do I need to use any react package?
The network tab screenshot might help you.
If I see in the network tab I get the same cookie, set among the other headers
To my understanding, fetch doesn't send requests with the cookies your browser has stored for that domain, and similarly, it doesn't store any cookies it receives in the response. This seems to be the expected behaviour of fetch.
To override this, try setting the credentials option when making the request, like so:
fetch(url, {
// ...
credentials: 'include'
})
or, alternatively:
fetch(url, {
// ...
credentials: 'same-origin'
})
You can read more about the differences between the two here.
I got my error resolved with two changings in my code
In front end just added credentials: 'include'
fetch(url, {
method : "POST"
body : body,
headers : headers,
credentials: 'include'
})
And in back end just replaced app.use(cors()); to
app.use(cors({ origin: 'http://localhost:3000', credentials: true, exposedHeaders: ['Set-Cookie', 'Date', 'ETag'] }))
That's it got resolved, Now I have cookies stored in my browser!!! Great. Thanks to this article:
https://www.anycodings.com/2022/01/react-app-express-server-set-cookie-not.html
during development i also faced same things, let me help you that how i solve it,
Firstly you use proxy in your react package.json, below private one:-
"private": true,
"proxy":"http://127.0.0.1:5000",
mention the same port on which your node server is running
Like:-
app.listen(5000,'127.0.0.1',()=>{
console.log('Server is Running');
});
above both must be on same , now react will run on port 3000 as usual but now we will create proxy to react So, react and node ports get connected on same with the help of proxy indirectly.
Now, when you will make GET or POST request from react then don't provide full URL, only provide the path on which you wants to get hit in backend and get response,
Example:-
React side on sending request, follow like this:-
const submitHandler=()=>{
axios.post('/api/loginuser',
{mobile:inputField.mobile,password:inputField.password})
.then((res)=>{
console.log(res);
})
.catch((err)=>{
console.log(err);
})
}
Node side where it will hit:-
app.post('/api/loginuser', async(req,res)=>{
//Your Code Stuff Here
res.send()
}
on both side same link should hit, it is very important
it will 100%.
don't forget to mention
on node main main where server is listening

supertest changing url at every test

I'm new to backend development and i face a problem that i don't understand.
I set up the 1st route of my API called "health" who just return a simple message to know if my server is up.
This route looks to works as expected.
However,
when I try to test this route with the method "toMatchSnapshot" from
jest API, the test is not passing because of the in the url is changing constantly.
My test file "index.test.ts":
const request = supertest.agent(app);
describe("app", () => {
it("should return a successful response for GET /health", async () => {
const res = await request.get("/health");
res.header = omit(res.header, ["date"]);
expect(res).toMatchSnapshot();
});
});
index of the server "index.ts":
const app = express();
expressService(app);
if (require.main === module) {
app.listen(PORT, () => {
console.log("server started at http://localhost:" + PORT);
});
}
export default app;
my function "expressService":
const expressService = (app: Application) => {
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(api);
};
export default expressService;
My PORT variable: PORT = 3000;
- "url": "http://127.0.0.1:49694/health",
+ "url": "http://127.0.0.1:52568/health",
this is where the test is failing.
Thank you for your answers.
The doc of supertest says:
You may pass an http.Server, or a Function to request() - if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports.
You need to pass a Node.js http.Server object to supertest.agent(), then you can use the specific PORT for testing.
Here is the solution:
index.ts:
import express from 'express';
import expressService from './expressService';
import http from 'http';
const app = express();
const PORT = process.env.PORT || 3000;
expressService(app);
function createHttpServer() {
const httpServer: http.Server = app.listen(PORT, () => {
console.log('server started at http://localhost:' + PORT);
});
return httpServer;
}
if (require.main === module) {
createHttpServer();
}
export default createHttpServer;
expressService.ts:
import { Application } from 'express-serve-static-core';
import express, { Router } from 'express';
import cors from 'cors';
const expressService = (app: Application) => {
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
const api = Router();
api.get('/health', (req, res) => {
res.sendStatus(200);
});
app.use(api);
};
export default expressService;
index.spec.ts:
import createHttpServer from './';
import { agent } from 'supertest';
import { omit } from 'lodash';
const httpServer = createHttpServer();
const request = agent(httpServer);
afterAll(done => {
httpServer.close(done);
});
describe('app', () => {
it('should return a successful response for GET /health', async () => {
const res = await request.get('/health');
res.header = omit(res.header, ['date']);
expect(res).toMatchSnapshot();
});
});
Unit test result:
PASS src/stackoverflow/57409561/index.spec.ts (7.853s)
app
✓ should return a successful response for GET /health (61ms)
console.log src/stackoverflow/57409561/index.ts:12
server started at http://localhost:3000
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 1 passed, 1 total
Time: 8.66s
Snapshot:
// Jest Snapshot v1
exports[`app should return a successful response for GET /health 1`] = `
Object {
"header": Object {
"access-control-allow-origin": "*",
"connection": "close",
"content-length": "2",
"content-type": "text/plain; charset=utf-8",
"etag": "W/\\"2-nOO9QiTIwXgNtWtBJezz8kv3SLc\\"",
"x-powered-by": "Express",
},
"req": Object {
"data": undefined,
"headers": Object {
"user-agent": "node-superagent/3.8.3",
},
"method": "GET",
"url": "http://127.0.0.1:3000/health",
},
"status": 200,
"text": "OK",
}
`;
Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57409561
Simple enough solution:
const request = require('supertest'); // npm i -ED supertest
const app = require('../app'); // your expressjs app
const { url } = request(app).get('/'); // next, just use url
console.debug(url); // prints: http://127.0.0.1:57516/

I encountered a problem while working on my project on MERN Stack

I encountered a problem while working on my project on MERN Stack.
My React app is running on port 3000 and express api on 5000. What I encountered is, while adding 0auth functionality using redux, I am getting error like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource here. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."
Now the structure of my logic is like :
I have defined google strategy for passport. Defined routes in express route (http://localhost:5000/api/user/auth/google) and callback url (http://localhost:5000/api/user/auth/google/callback). Now when I am directly accessing "http://localhost:5000/api/user/auth/google", I am able to complete process, but when I am calling it through reducers from react app, I am getting above mentioned error.
My code is the following:
// Routes
router.get(
"/auth/google",
passport.authenticate("google", {
scope: ["profile", "email"]
})
);
router.get(
"/auth/google/callback",
passport.authenticate("google", {
failureRedirect: "/",
session: false
}),
function(req, res) {
var token = req.user.token;
console.log(res);
res.json({
success: true,
token: 'Bearer ' + token,
});
}
);
//Reducers Action
export const googleLoginUser = () => dispatch => {
axios
.get('api/users/auth/google')
.then((res) => {
//save to local Storage
const {
token
} = res.data;
// Set token to local storage
localStorage.setItem('jwtToken', token);
//set token to auth header
setAuthToken(token);
// Decode token to get user data
const decoded = jwt_decode(token);
console.log(decoded);
// set current user
dispatch(setCurrentUser(decoded));
})
.catch(err => {
console.log(err);
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
}
)
}
Allow CORS by using middleware for Express. Install CORS with npm install cors. Import CORS import cors from 'cors'. Use middleware with app.use(cors()) if your Express-instance is called app.
Example:
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors());
Let me know if it solves the problem

Post request in VueJs with undefined response

I am a beginner in VueJs and Expressjs. I am trying to make frontend side by Vuejs and backend by ExpressJs. I send a post request to the backend (expressJs) and :
1- Response is undefined
2- At the same time I can see 2 requests in chrome development tools. One is Option and another one is Post.
3- With postman there is no problem at all.
Here is the code of app.js in express
console.log('Server is running')
const express = require('express'),
bodyParser = require('body-parser'),
cors = require('cors'),
morgan = require('morgan');
app = new express();
//Setup middleware
app.use(cors());
app.use(morgan('combined'))
app.use(bodyParser.json())
app.post('/register', (req, res, next) => {
res.send({
message: `Hello ${req.body.email}! your user was registered!`
})
});
app.listen(8081);
And here is the code in VueJs :
// Api Setting
import axios from 'axios'
export const HTTP = axios.create({
baseURL: `http://localhost:8081`
});
// AuthenticationService
import { HTTP } from '../services/Api'
export default {
register(credentials) {
HTTP.post('register', credentials);
}
}
// Register Component
export default {
data() {
return {
email: '',
password: ''
};
},
methods: {
async register() {
const response = await AuthenticationService.register({
email: this.email,
password: this.password
});
console.log(response); // the value is undefined
}
}
};
I really don't know what I missed here that I get an undefined response and 2 requests at the same time. I appreciate any hint.
Whole code on github repo : here
Maybe. Authentication.register is not returning anything or more specifically a Promise which should be used to populate const response in the await call.
Try returning something like so: return HTTP.post('register', credentials); inside register.
For this to work though, HTTP.post('register', credentials) should also return something.
I use JSON.stringify to send the data, you are sending the objects directly, so
register(credentials) {
HTTP.post('register', credentials);
}
becomes
register(credentials) {
HTTP.post('register', JSON.stringify(credentials));
}

Categories