Flutter & GraphQL - express

Not sure why am I getting this error.
Please help.
const express = require('express');
const graphqlHTTP = require('express-graphql');
const app = express();
app.use('/graphql', graphqlHTTP({
graphiql: true
}));
app.listen(4000, () => {
console.log('Listening to port 4000');
});

From their doc
const { graphqlHTTP } = require('express-graphql');

Related

Can't receive a response message when using proxy-middleware between react ui and express backend

I see that the request sent from the ui created using React is forwarded to the backend, but I can't get the response from the ui. There may be details that I missed as I am very new to these issues, thanks in advance :)
//react Login.js
function Login() {
const fetch = actions.fetchUser();
async function handleSubmit() {
try {
fetch();
} catch (err) {
console.error('err', err);
}
}
export default Login;
//index.js
import axios from 'axios';
export const fetchUser = () => async () => {
await axios.get('/api/login');
};
//setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
['/api'],
createProxyMiddleware({
target: 'http://localhost:5000',
}),
);
};
//express app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 5000;
app.use(cors());
app.use(bodyParser.json());
require('./routes/login')(app);
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
// espress login.js
module.exports = app => {
app.get('/api/login', (req, res) => {
console.error('express login');
res.send('login');
});
First of all, do not mix cjs and mjs import/exports.
second of all, you export your middleware but never register/use it. At least your code does not show that part.
Here is very minimal example how you can proxy your react UI via express.
const express = require('express');
const proxy = require('express-http-proxy');
const app = express();
app.get('/api', (req, res) => {
res.send({my: 'data'});
});
// register other routes here
app.use(proxy('http://127.0.0.1:3000'));
app.listen(5000, '0.0.0.0', () => {
console.log('Server is running at http://127.0.0.1:5000');
});
React app content will be available on http://127.0.0.1:5000 with your routes.
And http://127.0.0.1:5000/api will be your express route.
Note: I assume your react app runs on the port 3000

axios doesn't send post for Stripe

I have a problem with axios Post. I work on adding Stripe payment to my page, but i send me axios error 404.
Maybe somebody can help me, I stuck on it for week already and cant just solve it.
Here is the code:
import React from 'react'
import StripeCheckout from 'react-stripe-checkout';
import { useState, useEffect } from "react";
import { useNavigate } from 'react-router-dom';
import axios from "axios";
const Pay = () => {
const [stripeToken, setStripeToken] = useState(null)
const navigate = useNavigate()
const onToken = (token) => {
setStripeToken(token);
}
useEffect(() => {
const makeRequest = async () => {
try {
const res = await axios.post(
"http//:localhost:5001/api/checkout/payment",
{
tokenId: stripeToken.id,
amount: 6000,
});
console.log(res.data)
} catch (err) {
console.log(err)
}
};
stripeToken && makeRequest()
}, [stripeToken]);
return (
<div className='pay__div'>
{stripeToken ? (<span>Processing</span>) : (
<StripeCheckout
name="Kate store"
image=""
billingAddress
shippingAddress
description="Yout total is $60"
amount={2000}
token={onToken}
stripeKey={KEY}
>
<button>Pay</button>
</StripeCheckout>
)}
</div>
)
}
export default Pay
Thank you for your time.
Also here are stripe.js index.js pages from backend
stripe.js
const router = require("express").Router();
const stripe = require("stripe")(process.env.STRIPE_KEY);
router.post("/payment", (req, res) => {
stripe.charges.create({
sourse: req.body.tokenId,
amount: req.body.amount,
currency: "usd"
},
(stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).json(stripeErr);
} else {
res.status(200).json(stripeRes);
}
});
});
module.exports = router;
And index.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const userRoute = require("./routes/user");
const authRoute = require("./routes/auth");
const productRoute = require("./routes/product");
const cartRoute = require("./routes/cart");
const orderRoute = require("./routes/order");
const stripeRoute = require("./routes/stripe");
const cors = require("cors");
dotenv.config();
mongoose.connect(process.env.MONGO_URL)
.then(() => console.log("DB Connected Successfull!"))
.catch((err) => {
console.log(err);
})
app.use(cors());
app.use(express.json());
app.use("/api/user", userRoute);
app.use("/api/auth", authRoute);
app.use("/api/product", productRoute);
app.use("/api/cart", cartRoute);
app.use("/api/order", orderRoute);
app.use("/api/checkout", stripeRoute);
app.listen(process.env.PORT || 5001, () => {
console.log("Backend is running")
})
Had the same problem. Moved dotenv.config(); before const stripeRoute = require("./routes/stripe"); in index.js and worked.

i18next dropdown select without reactjs

I need to create a dropdown in order to select languages in the website. I only use nodejs not react. How can I create it? My codes are at the below.enter image description here
const express = require('express');
const app = express();
const ejs = require('ejs');
const i18next = require('i18next');
const Backend = require('i18next-fs-backend');
const i18nextMiddleware = require('i18next-http-middleware');
i18next
.use(Backend)
.use(i18nextMiddleware.LanguageDetector)
.init({
fallbackLng: 'tr',
lng: 'tr',
backend: {
loadPath: './translate/{{lng}}.json',
},
});
app.use(i18nextMiddleware.handle(i18next));
app.use(express.json());
app.set('view engine', 'ejs');
const stdI18next = { t: i18next.t.bind(i18next.t) };
app.get('/', (req, res) => {
res.render('index', stdI18next);
});
app.get('/test', (req, res) => {
res.render('test', stdI18next);
});

cors error preflight alow origin mismatch for apollo client and sever

Overview
I am trying to get authentications set up in Apollo but I keep running into this network error: CORS error PreflightAllowOriginMismatch. I have looked and tried so many solutions on the internet but nothing is working.
I have my client running on localhost:3000 and my server on localhost:4000.
Code
//client index.js
import React from 'react';
import { render } from 'react-dom';
import { ApolloProvider } from '#apollo/client';
import App from './App';
import { ApolloClient, createHttpLink, InMemoryCache } from '#apollo/client';
const httpLink = createHttpLink({
uri: 'http://localhost:4000/graphql',
credentials: 'include',
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
render((
<ApolloProvider client={client}>
<App />
</ApolloProvider>
), document.getElementById('root')
);
//server index.js
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const cors = require('cors');
const schema = require('./schema');
const models = require('./sequelize/models');
const server = new ApolloServer({
schema,
context: req => ({
...req,
models,
})
});
const app = express();
var corsOptions = {
origin: 'http://localhost:3000/',
credentials: true // <-- REQUIRED backend setting
};
app.use(cors(corsOptions));
server.applyMiddleware({ app, cors: false });
app.listen({ port: 4000 });
I'm honestly lost at this point. I new to apollo and for the life of me cannot find what i am missing.
Although I am unsure about the security the following changes fixed my issue.
remove
origin: 'http://localhost:3000/',
credentials: true // <-- REQUIRED backend setting
};
app.use(cors(corsOptions));
update
server.applyMiddleware({ app, cors: {credentials: true, origin: true} });
the final file:
//server index.js
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const schema = require('./schema');
const models = require('./sequelize/models');
const server = new ApolloServer({
schema,
context: req => ({
...req,
models,
})
});
const app = express();
server.applyMiddleware({
app,
cors: {credentials: true, origin: true}
});
app.listen({ port: 4000 });

fetch POST request is pending (sending data from registration form)

I know that similar questions have already been here, but I didn't find anything for my problem.
I am creating project using [Webpack-Express-Pug-VanillaJS] stack of technologies.
I'm trying to make POST-request to send formData to '/api/users' using fetch a push data to array in my express file, but its only pending...
What kind of problems it can be?
client-side code
document.addEventListener('DOMContentLoaded', () => {
async function postData(url, data) {
try {
console.log('addEventListener works!')
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
console.log('fetch works!')
return await response.json()
} catch(e) {
console.warn('Error',e.message)
}
}
const forms = document.getElementsByTagName('FORM');
for (let i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(e) {
console.log(forms[i])
e.preventDefault();
let formData = new FormData(this);
formData = Object.fromEntries(formData);
console.log(formData) return object like {name:'Zhanna', age:25, email:'123zhanna#gmail.com'}
postData('/api/users', formData).then(data => console.log('Successful!'))
})
}
})
server-side
const path = require('path')
const express =require('express')
const webpack = require('webpack')
const bodyParser = require('body-parser')
const users = require('../routes/userInfo')
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import config from '../../webpack.dev.config.js'
import { v4 } from 'uuid';
const PORT = process.env.PORT || 8080
const app = express(),
compiler = webpack(config)
app.use(users.router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.json());
app.set('views', path.join(__dirname, "views"));
app.set('view engine', 'pug');
app.locals.basedir = __dirname;
app.use('/assets',express.static(path.join(__dirname,'assets')))
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
})
)
app.use(webpackHotMiddleware(compiler))
app.get('/registration', (req,res)=> {
res.status(200).render('registration')
})
app.get('/login', (req,res)=> {
res.status(200).render('signIn')
})
app.get('/', (req, res) => {
res.status(200).render('index')
}
)
app.get('/api/users', (req,res)=> {
res.status(200).json(users.list)
})
app.post('/api/users', (req,res)=> {
const user = {...req.body, id:v4()}
users.list.push(user)
console.log('Data was sent')
res.status(201).json(user)
})
app.listen(PORT, () => {
console.log(`App listening to ${PORT}....`)
console.log('Press Ctrl+C to quit.')
})
And in my console there is only 3 logs:
addEvent listener works!
<form class="registration--form" id="send-form">...<form>
3.{name: "Zhanna", surname: "Kaymedenova", gender: "female", brth: "07.01.1994", email: "zh.kaymed#gmail.com"}