Cookie not set even after configuring - javascript

I am trying to set cookie in browser by sending name data from register page to backend. It receives the name and console logs it correctly but i cannot see any cookie being set in chrome dev tools even after all the configurations.
Below is my server.js file
require("dotenv").config()
const express = require('express')
const cors = require('cors')
const cookieParser = require("cookie-parser")
const app = express()
app.use(cors({
origin: 'http://localhost:3000',
optionsSuccessStatus: 200 ,
credentials:true
}))
app.use(function(req, res, next) {
res.header('Content-Type', 'application/json;charset=UTF-8')
res.header('Access-Control-Allow-Credentials', true)
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
)
next()
})
app.use(express.json())
app.use(express.urlencoded({extended:false}))
app.use(cookieParser())
app.post('/register',function(req,res){
res.cookie("name",req.body.name)
console.log(req.body.name)
})
app.listen(5000, () => {
console.log("Server running on Port 5000")
})
Below is my App.js from frontend
import './App.css';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
import Register from './pages/Register';
import axios from 'axios'
axios.defaults.withCredentials=true
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route path='/' element={<Register/>}/>
</Routes>
</Router>
</div>
);
}
export default App;
Below is my Register.jsx
import React,{ useState } from 'react'
import axios from 'axios'
const Register = () => {
const [name,setName]=useState('')
const handleSave = async()=>{
const response = await axios.post('http://localhost:5000/register',{name:name},{
withCredentials: true,
})
console.log(response.data)
}
return (
<div>
<label>Name:</label>
<input value={name} onChange={(e)=>setName(e.target.value)}></input>
<button onClick={handleSave}>Send</button>
</div>
)
}
export default Register
Below is my Response Headers from chrome network tab
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: http://localhost:3000
Connection: keep-alive
Content-Length: 0
Date: Sun, 15 Jan 2023 17:16:18 GMT
Keep-Alive: timeout=5
Vary: Origin, Access-Control-Request-Headers
X-Powered-By: Express
I tried various configurations from various sources but nothing is working. Any help is very much appreciated. Thank you.

Related

React Router not working correctly on production with express backend

I have Single page application built with React and Express as backend.
There are only two pages/main components: the application(<SinglePage/ >) and Not found page(<PageNotFound / >).
I want to display the application when "/" url is requested and to display the Not Found when any other url is requested(for example /home, /test, /insertInvalidUrlHere etc.).
This logic works perfectly on Localhost, but when I deploy the app to the domain, the single page view is displayed correctly(on url '/'), but when any other url is requested the attached page below is displayed, not the Not found page as expected. I also found out that the Not found page is displayed only if index.html is appended to the URL(domain.com/index.html).
I already tried these:
placing <Navigate to"/404"/> at the end and changing the route path to "/404".
changing the route path to "" or entirely removing it.
using HashRouter
deleting the app and deploying it again and again from the start.
None of these worked.
I also tried to build the app locally, and then use http-serve ( npm i -g http-serve ) to serve the build folder. Everything is displayed correctly in this case.
Could you please advise me, what I am doing wrong and what should be amended in order for the logic to work correctly when I deploy the app to the domain.
Frontend: App.tsx
import { BrowserRouter as Router , Route, Routes} from "react-router-dom";
import PageNotFound from "./Components/PageNotFound/PageNotFound";
import SinglePage from "./SinglePage";
function App() {
return (
<>
<Router>
<Routes>
<Route path="/" element={<SinglePage />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
</Router>
</>
);
}
export default App;
Backend: App.ts
const express = require("express");
const nodemailer = require("nodemailer");
const cors = require("cors");
const request = require("request");
var https = require('https');
var fs = require('fs');
const app = express();
app.use(express.json());
app.use(cors());
let transporter = nodemailer.createTransport({
host: "mail.mail.com",
port: 465,
secure: true,
auth: {
user: "user#test.com",
pass: "TestPassword123",
}
});
transporter.verify((err, success) => {
err
? console.log(err)
: console.log(`Server is ready to receive messages: ${success}`);
});
app.post("/send", function (req, res) {
let mailOptions = {
from: `${req.body.mailerState.email}`,
to: "test#gmail.com",
subject: `Message from: ${req.body.mailerState.email}`,
text: `${req.body.mailerState.message}`,
};
transporter.sendMail(mailOptions, function (err, data) {
if (err) {
res.json({
status: "fail",
});
} else {
console.log("Message Sent");
res.json({
status: "success",
});
}
});
});
const port = 3001;
https
.createServer(
{
key: fs.readFileSync("key.pem"),
cert: fs.readFileSync("cert.pem"),
},
app
)
.listen(port, () => {
console.log("Server is running at port 3001");
});
app.get('/', (req, res) => {
res.send("Hello from express server.")
})
I assume the error is locating in your router - since you have path="/" first, all subsequent urls ("/home","/test","/error/404", etc) will hit this path. try to use exact so your routing looks like this:
<Routes>
<Route path="/" exact element={<SinglePage />} />
<Route path="*" element={<PageNotFound />} />
</Routes>

Keep getting error with simple ReactJS FORM posting to Express JS server

I am new to ReactJS and trying to find a way to connect my React front end to my Express js backend. To do this, I am just setting up a simple form that sends a POST request after I press a register button in a form.
The problem is I keep getting these error messages in the console.
These are the errors
POST http://localhost:3000/api/users 404 (Not Found)
Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.onloadend (xhr.js:66)
This is the react code
import Proj from './Proj'
import React, {Fragment, useState} from 'react'
import axios from 'axios';
export const Homepage = () => {
const [formData, setFormData] = useState({
name:'',
});
const { name } = formData;
const onChange = e =>
setFormData({...formData, [e.target.name]:e.target.value})
const onSubmit = async e => {
console.log('submitted')
e.preventDefault();
const newUser = {
name,
}
try {
const config = {
headers:{
'Content-Type':'application/json'
} }
const body = JSON.stringify(newUser)
const res = await axios.post('/api/users',body, config)
console.log(res)
} catch (err) {
console.error(err)
}
}
return (
<div className="Landing">
<Proj/>
<section>
<form onSubmit = {e=>onSubmit(e)}>
<input
type="text"
placeholder="Name"
name="name"
value = {name}
onChange = {e =>onChange(e)}
required />
<input type="submit" className="btn btn-primary" value="Register" />
<h1>Contact</h1>
</form>
</section>
</div>
)
}
export default Homepage
This App.js
import { Navbar } from './components/Navbar';
import Homepage from './components/Homepage';
import Projects from './components/Projects';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import './App.css';
function App() {
return (
<Router>
<div className="App">
<Navbar/>
</div>
<Route exact path="/" component={Homepage} />
<Switch>
<Route exact path="/Projects" component={Projects} />
</Switch>
</Router>
);
}
export default App;
This is my server side JS
const express = require ('express')
const path = require('path');
const app = express()
app.use(express.urlencoded({extended: false}));
app.use('/', require('./routes/api/users'))
// Serve static assets in production
if (process.env.NODE_ENV === 'production'){
app.use(express.static('client/build'))
app.get('*', (req,res)=>{
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
})
}
const PORT = 5000
app.listen(process.env.PORT || 5000)
and this is users.js in the api folder in routes
const express = require('express')
const router = express.Router();
router.post('/', async (req,res)=>
{
console.log('its working, and here is the data', req.body)
})
module.exports = router;
client side package.json
"proxy":"http://localhost:5000",
I would really appreciate it if someone can tell me what I am doing wrong or if there is a better way to do things.Thanks.
Instead of
app.use('/', require('./routes/api/users'))
type in
app.use('/api/users', require('./routes/api/users'))
You are posting currently to a route that does not exist.

axios GET request not working in MERN application [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So, I am attempting a simple, single-page application on the MERN stack that takes notes - a note title and a note content and displays them on the same root route; the data is supposed to also be saved on the backend for later retrieval. At this time, there is no authentication. My backend seems to be working perfectly, but when I connect the front end React application to the backend MongoDB database, my GET request (using axios instance) fails.
My backend renders on localhost:5000, no problem.
But on localhost:3000, I'm seeing this error in App.jsx:
Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
Here's what I have going on:
BACKEND
// server.js
import express from 'express';
import cors from 'cors';
import notes from './api/notes.route.js';
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/api/v1/notes', notes);
app.use('*', (req, res) => res.status(404).json({ error: 'not found' }));
export default app;
// notes.route.js
import express from 'express';
import NotesController from './notes.controller.js';
const router = express.Router();
router
.route('/')
.get(NotesController.apiGetNotes)
.post(NotesController.apiPostNote)
.put(NotesController.apiUpdateNote)
.delete(NotesController.apiDeleteNote);
export default router;
// notes.controller.js
import NotesDAO from '../dao/notesDAO.js';
class NotesController {
static apiGetNotes = async (req, res, next) => {
const notesPerPage = req.query.notesPerPage
? parseInt(req.query.notesPerPage)
: 20;
const page = req.query.page ? parseInt(req.query.page) : 0;
const { notesList, totalNumNotes } = await NotesDAO.getNotes({
page,
notesPerPage
});
let response = {
notesList,
page,
notesPerPage,
totalNumNotes
};
res.json(response);
};
export default NotesController;
// notesDAO.js
import mongodb from 'mongodb';
const ObjectID = mongodb.ObjectId;
let notes;
class NotesDAO {
// call this on db connection:
static injectDB = async conn => {
if (notes) return;
try {
notes = await conn.db(process.env.NOTESDB_NS).collection('notes');
} catch (e) {
console.error(`unable to establish collection handle in notesDAO: ${e}`);
}
};
static getNotes = async ({ page = 0, notesPerPage = 20 } = {}) => {
let query;
let cursor;
try {
cursor = await notes.find(query);
} catch (e) {
console.error(`unable to issue find command, ${e}`);
return { notesList: [], totalNumNotes: 0 };
}
const displayCursor = cursor.limit(notesPerPage).skip(notesPerPage * page);
try {
const notesList = await displayCursor.toArray();
const totalNumNotes = await notes.countDocuments(query);
return { notesList, totalNumNotes };
} catch (e) {
console.error(
`unable to convert cursor to array or problem counting documents, ${e}`
);
return { notesList: [], totalNumNotes: 0 };
}
};
}
export default NotesDAO;
FRONTEND
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Route path="/" component={App} />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
// App.jsx
import { useState, useEffect } from 'react';
import NoteDataService from './services/note.js';
import Header from './Header';
import Footer from './Footer';
import CreateArea from './CreateArea';
import Notes from './Notes';
const App = () => {
const [notes, setNotes] = useState([]);
useEffect(() => {
retrieveNotes();
}, []);
const retrieveNotes = async () => {
await NoteDataService.getAll()
.then(response => {
console.log(response.data);
setNotes(response.data.notes);
})
.catch(e => console.log(e));
};
return (
<>
<Header />
<CreateArea clicked={addNote} />
<Notes notes={notes} clicked={deleteNote} />
<Footer />
</>
);
};
export default App;
// http-common.js
import axios from 'axios';
export default axios.create({
baseURL: 'http://localhost:5000/api/vi/notes',
headers: {
'Content-type': 'application/json'
}
});
// note.js
import http from '../http-common.js';
class NoteDataService {
getAll() {
return http.get('/');
}
}
export default new NoteDataService();
You have a typo. The backend route is /api/v1/notes, but the frontend is sending requests to /api/vi/notes

XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' Google maps

I am new to React js I am trying to simple dynamically changing map with respected to user input But for specific place seach request this error rises
XMLHttpRequest cannot load
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=undef…ined&radius=1000&keyword=fdtbf&key=myapikey.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
this is my node js code
import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
//Import To Pord
import api from './routes/api';
import auth from './routes/auth'
import cookieParser from 'cookie-parser';
import {LoginCheck} from './middleware/authCheck';
import cors from 'cors';
//All Webpack Stuff
import webpackConfig from '../../webpack.config.dev';
import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware'
import webpackHotMidleware from 'webpack-hot-middleware';
//Server Side Rendering Stuff
import {match, RouterContext } from 'react-router';
import { Provider } from 'react-redux';
import { dispatch } from 'redux';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import reducer from '../../src/client/Reducers';
import routes from '../client/routes';
import thunk from 'redux-thunk';
import { createStore ,applyMiddleware} from 'redux'
import React from 'react'
import Helmet from 'react-helmet';
import serialize from 'serialize-javascript';
//PassPort Stuff Import This
let app = express();
app.use(bodyParser.json());
app.use(express.static('public'))
const compiler = webpack(webpackConfig);
app.use(webpackMiddleware(compiler, {
hot: true,
publicPath: webpackConfig.output.publicPath,
noInfo: true
}));
app.use(webpackHotMidleware(compiler));
app.use(cors());
app.use(cookieParser('sdkhcvlsd684684JJJklvblsdkuvgblsduvblsidvksdjbvlsjvuywlsfvliusdgv'));
//Check Auth MiddleWare
app.use(LoginCheck)
//Passport Api
app.use('/auth',auth);
//Our Api
app.use('/p',api);
app.get('/*', (req, res,next) => {
// res.sendFile(path.join(__dirname, '../../index.html'))
// Server Side Rendering Starts
match({routes:routes(),location:req.url},(err,redirectLocation,renderProps) => {
if (err) return next(err);
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
}
// if (!renderProps) {
// res.redirect('/404')
// }
const components = renderProps.components;
const Comp = components[components.length - 1].WrappedComponent;
const fetchData = (Comp && Comp.fetchData) || (() => Promise.resolve())
const initialState = {}
const store = createStore(reducer, initialState, applyMiddleware(thunk));
const { location, params, history } = renderProps
fetchData({ store, location, params, history }).then(() => {
const body = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
const state = store.getState();
// console.log(state)
let head = Helmet.rewind();
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.send(`<!DOCTYPE html>
<html>
<head>
${head.title}
${head.meta}
${head.link}
</head>
<body>
<div id="app" >${body}</div>
<script>window.__STATE__=${JSON.stringify(state)}</script>
<script src="/bundle.js"></script>
</body>
</html>`)
})
.catch((err) => next(err))
})
});
app.listen(3000 ,() => {
console.log('Listening')
});
this is my axios request
export function getPlaceFromCoords(term,coords) {
// https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=13.0826802,80.2707184&radius=500&keyword=parks&key=AIzaSyAZbur2hq7p3UxjYrA2_G4ctpswFi0pO3A
console.log(coords)
return dispatch => {
return axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${coords.lat},${coords.lng}&radius=1000&keyword=${term}&key=${config.MAP_API}`).then(response => {
return response.data
})
}
}
The CORS headers are not set for Places API web service on Google backend servers. So you won't be able to call Places API web service from the client side JavaScript code due to the Same-Origin policy of the browsers.
In order to use Places on client side JavaScript you have to use a Places library of Google Maps JavaScript API. The places library has nearby, radar and text search functionality very similar to the corresponding web service.
For further details please have a look at the documentation:
https://developers.google.com/maps/documentation/javascript/places
Hope it helps!

React Router is able to do the routing only if started from root url

I have a React app that also uses Redux and ReactRouter.
My problem is the following:
When I launch the app and go to the root url, I can normally navigate inside the app, and the routes in the navigation bar will be changing as I navigate.
However, if I type in the navigation bar any url other than the root, I get a weird error:
I don't really get how one can get such an error.
If I go to localhost:1337/ and then click on the item with the link /cars/1, everything will be fine and the component will successfully get rendered. If I type localhost:1337/cars/1 right away (or any other existing route) I get this error.
Here's how I initialize the react-router and define my routes:
index.js:
require('./style/style.css');
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, browserHistory } from 'react-router';
import reduxPromise from 'redux-promise';
import routes from './routes';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(
reduxPromise
)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.querySelector('.container.app')
);
routes.js:
import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
import App from './components/app';
import CarsIndex from './containers/cars-index';
import CarNew from './containers/car-new';
import CarShow from './containers/car-show';
import CarEdit from './containers/car-edit';
import SignIn from './containers/signin';
import auth from './auth/auth';
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/authenticate',
state: { nextPathname: nextState.location.pathname }
});
}
}
function filterLoggedIn(nextState, replace) {
if (auth.loggedIn()) {
replace({
pathname: '/',
state: { nextPathname: nextState.location.pathname }
});
}
}
export default (
<Route path='/' component={App}>
<IndexRoute component={CarsIndex} onEnter={requireAuth} />
<Route path='cars/new' component={CarNew} onEnter={requireAuth} />
<Route path='cars/:id' component={CarShow} onEnter={requireAuth} />
<Route path='cars/edit/:id' component={CarEdit} onEnter={requireAuth} />
<Route path='authenticate' component={SignIn} onEnter={filterLoggedIn} />
<Redirect from='*' to='/' />
</Route>
);
My server is a small express.js app and it redirects any requests other than /api/* to the index.html page.
Here's a part from my server.js:
const path = require('path');
const port = process.env.PORT || 1337;
const app = express();
const pathToStatic = path.join(__dirname, 'static');
express.static(path.join(__dirname, 'static'));
app.use(express.static(pathToStatic));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/api/cars', (req, res) => {
return Car.find((err, cars) => {
if (!err) {
return res.send(cars);
} else {
console.log(err);
res.statusCode = 500;
return res.send({ error: 'Server error' });
}
});
});
app.get('*', (req, res) => {
res.sendFile(path.resolve(pathToStatic, 'index.html'));
});
app.listen(port, () => {
console.log(`Express server is listening on port ${port}`);
});
Have you encountered such an issue? Could you help me to find out the soultion to this problem?
The screenshot shows that bundle.js (when requested) is returning index.html.
This is because your express routes handle route api/cars and then default everything else to index.html.
Of course all your resources that appear on index.html must also be sent the browser. This includes <script src="bundle.js"></script> which the browser will request once it gets index.html the first time.
So, you must have some way to allow express to handle requests for the resources that index.html needs.
A popular solution to this is to mount an assets directory and place that above the default route. Something like:
// api routes
app.use(express.static('assets'));
// default route
Then make sure your bundle.js is inside the assets directory. And then that the script tag looks like <script src="/assets/bundle.js"></script>.

Categories