I'm trying to connect to stripe server using express framework but I keep getting this error in the image I attached above.
import express from "express";
const app = express();
const port = 3000;
const PUBLISHABLE_KEY = "pk_test......";
const SECRET_KEY = "sk_test.........";
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
You have not did a GET method. Try to do - above the listening:
app.get('/',(req, res)=>{
res.send('Hello World')
});
Now, when you call http://localhost:3000/ you will see Hello World.
Related
I'm new to Axios, and I was trying to fetch data from an endpoint to use in React...
import axios from "axios";
const api = axios.create({ baseURL: "http://localhost:5000/" });
export default function App() {
api.get("/products").then(res => console.log(res.data));
...
}
Here is my endpoint code...
const express = require("express");
const app = express();
require("dotenv").config();
app.get("/products", (req, res) => {
res.send("Hello world!");
});
const port = process.env.PORT;
app.listen(port, () => console.log(`Listening on port ${port}...`));
But instead of the Hello world! getting logged I am getting this error...
Any help would be appreciated.
Hi look for this lib Cors for express and you can use proxy in react project in your package.json instead of axios.create()
like
"proxy": "http://localhost:5000"
Install cors middleware in your backend server.
npm install cors
Enable all CORS requests
const express = require("express");
var cors = require('cors')
const app = express();
app.use(cors())
You can look for more information here. There are ways to configure your CORS as well.
To your another question, CRUD operations should be used in useEffect hook.
import React, { useEffect } from 'react';
export default function App() {
useEffect(() => {
api.get("/products").then(res => console.log(res.data));
}, [])
...
}
I currently have the following folder structure and will deploy in Heroku. I will remove if it's duplicated but I couldn't find proper answer
-Client
-Google.js (contains CLIENT id)
-App.js
-package.json
-env
server.js
models
routers
package.json
env
My Google.js contains app id and env is prefixed with REACT_APP_CLIENT_ID
I have used proxy https://localhost:5000 in Client package.json
My server.js - I am accessing static client files here
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path')
const app = express();
require('./database');
require('dotenv').config()
app.use(bodyParser.json());
app.use(cors());
const users = require('/api/users');
app.use('/api/users', users);
app.use(express.static(path.join(__dirname, '../build')))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../build'))
})
-----
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
When I have 2 env files, It runs perfectly. But when I try to run only with my server and deploy in heroku, client env cannot be accessed from server.
I understand client and server env should be separated. But is there any way, I could ACCESS Google.js env file(present in client folder) from single env file in my root folder?
My Google.js
import React from 'react';
import ReactDOM from 'react-dom';
import GoogleLogin from 'react-google-login';
const responseGoogle = (response) => {
console.log(response);
}
ReactDOM.render(
<GoogleLogin
clientId={`${process.env.REACT_APP_CLIENT_ID}`}
buttonText="Login"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={'single_host_origin'}
/>,
document.getElementById('googleButton')
);
Proxy error: Could not proxy request /api/games from localhost:3000 to http://localhost:8080/ (ECONNREFUSED).
code in action.js (Redux)
export function fetchGames(){
return dispatch =>{
fetch('/api/games')
}
}
import express from 'express';
import mongodb from 'mongodb';
const app = express();
const dbUrl = 'mongodb://onkar localhost:27017/crudwithredux';
mongodb.MongoClient.connect(dbUrl, function(err, db) {
app.get('/api/games', (req, res) => {
db.collection('games').find({}).toArray((err, games) => {
res.json({ games });
});
});
app.listen(8080, () => console.log('Server is running on localhost:8080'));
});
** Hi i m onkar, I am new in react js. i getting error in server page. I have mongo db database so i m retrieve the data from mongo db. and show in Json format in react js using redux.**
I am learning GraphQL using with React, but stuck at routing issue.
This is mostly from the express, App works fine on the home route "localhost:4000/", but other then this "localhost:4000/song" , I get 'Cannot GET /song' error.
Here's full code: Lyrical-GraphQL Demo
Here's my server.js file:
const express = require('express');
const models = require('./models');
const expressGraphQL = require('express-graphql');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const schema = require('./schema/schema');
const app = express();
// Replace with your mongoLab URI
const MONGO_URI = 'mongodb://XXX:XXX#ds123371.mlab.com:23371/lyricaldb';
if (!MONGO_URI) {
throw new Error('You must provide a MongoLab URI');
}
mongoose.Promise = global.Promise;
mongoose.connect(MONGO_URI);
mongoose.connection
.once('open', () => console.log('Connected to MongoLab instance.'))
.on('error', error => console.log('Error connecting to MongoLab:', error));
app.use(bodyParser.json());
app.use('/graphql', expressGraphQL({
schema,
graphiql: true
}));
const webpackMiddleware = require('webpack-dev-middleware');
const webpack = require('webpack');
const webpackConfig = require('../webpack.config.js');
app.use(webpackMiddleware(webpack(webpackConfig)));
module.exports = app;
You need to define routes and respective component to render. This can be of help,
https://gist.github.com/siakaramalegos/df4620c52e829f6107c75d5c3f0ad7f5
That's because the request is going to the server. The error you're seeing is from express server.
You'll need to add a handler in server.js to capture all other requests something like this
app.get('*', function(req, res) {
res.sendfile('path-to-your-index-html');
});
Infact, I think this post might be useful.
I solved the problem, actually the issue was not from the server side routing, it was confussion between HashRouter and BrowserRouter of react-router.
Currently I'm using HashRouter and it is working fine. For BrowserRouter, you need to set up all routes prooperly from the server side.
Thanks Community!
I have almost googled my fingers off trying to figure this out. It seems a lot of the existing info on connecting socket.io with React Native is outdated, or maybe I'm just interpreting things wrong?
I've managed to get the client-side connected (I'm getting the client console logs when I connect to my app). It seems to be the server-side that's giving me issues. Why is the data being emitted from the client not showing up as a log in my terminal? None of the related console.logs in my server.js are logging but the App.js console.logs are registering.
Edit: Here is my full App.js file:
import Expo from 'expo';
import React from 'react';
import { Dimensions, StyleSheet, Text, View } from 'react-native';
import store from './src/store';
import { Provider } from 'react-redux';
// window.navigator.useragent = 'react-native'; -> not necessary anymore?
const ROOT_URL = 'https://myherokudomain.herokuapp.com';
const io = require('socket.io-client/dist/socket.io');
const socket = io.connect(ROOT_URL);
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('example', (data) => {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
});
export default class App extends React.Component {
render() {
// const MainNavigator = my react-navigation system
return (
<Provider store={store}>
<View style={styles.container}>
<MainNavigator />
</View>
</Provider>
);
}
}
Edit: Here is my full server.js file:
const config = require('./config/config');
const { mongoose } = require('./db/mongoose');
const express = require('express');
const cors = require('cors');
const app = express();
const port = process.env.PORT;
// ************ Include and use separate routes file
app.use(require('./routes/routes'));
// ************
//Cross-Origin resource sharing. cors library solves CORS problems.
app.use(cors());
//***********
/* Chat server code*/
// enabled heroku session affinity:
// see https://devcenter.heroku.com/articles/session-affinity
// to enable: heroku features:enable http-session-affinity
// to diable: heroku features:disable http-session-affinity
const socketIO = require('socket.io');
const http = require('http');
const server = http.createServer(app);
const io = socketIO(server, { origin: "*:*" });
//********** */
io.on('connection', (socket) => {
console.log('A client just joined', socket.id);
socket.emit('example', { hello: 'world' });
socket.on('my other event', (data) => {
console.log(data);
});
socket.on('disconnect', () => {
console.log('User was disconnected');
});
});
server.listen(port, (err) => {
console.log(`started on port ${port}`);
});
module.exports = { app };
I am getting the console logs on the client side just fine (for instance, the "connected to server" and "hello: world" stuff is showing up when I open my app on expo. But I am not getting the server-side console logs.
What am I doing wrong - how do I get socket.io fully working with a deployed React-Native app?
I would really appreciate any help at all! I've been stuck on this forever.
I'm assuming all the code works, just not the logging since that's all you're asking about. The problem is Node doesn't output to your browser's console.
If it's deployed on heroku then you should see everything being logged there, otherwise you can use libraries like https://github.com/node-inspector/node-inspector to output to your browser.
You're not getting the server-side console logs because 1.) They're only logging on the server, and 2.) You're not emitting them, if you do actually want to send the data back.