ReactJS code
import axios from 'axios';
import {useEffect,useState} from 'react';
import ReactDOM from "react-dom/client";
import React from "react";
const App = () => {
const [res,setRes] = useState(null)
useEffect(() => {
document.cookie='hello=3';
axios.post('http://localhost:4000/hello').then(res1 => {
setRes(res1.data)
})
},[])
return (
<div>
{res}
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
Nodejs code
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
const PORT = 4000;
const app = express();
// cors
app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser())
app.post('/hello', (req, res) => {
console.log(req.cookies)
res.send('This is from server!')
})
app.listen(PORT, () => {
console.log('listening on port', PORT); // eslint-disable-line no-console
});
On the line of console.log(req.cookies) in node.js it gives
[Object: null prototype] {}
what is the issue?
You are sending request to a different domain. If you want to send cookies with that request you would have to add withCredentials property in request options.
axios.get(
'http://localhost:4000/hello',
{ withCredentials: true }
);
Related
I have set up custom koa.js server and every time I make a request to api for example
/api/login
It always ends up in being 404 not found.
I have tried looking for a solution but, could not really find it.
Below is my server.js file
import '#babel/polyfill';
import dotenv from 'dotenv';
import 'isomorphic-fetch';
import next from 'next';
import Koa from 'koa';
import Router from 'koa-router';
import UserRouter from './routes/user';
import cors from '#koa/cors';
dotenv.config();
const compression = require('compression');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = new Koa();
const router = new Router();
server.use(
cors({
origin: '*',
})
);
router.get('*', async (ctx) => {
await handle(ctx.req, ctx.res);
ctx.respond = false;
});
server.use(UserRouter.routes()).use(UserRouter.allowedMethods());
server.use(router.allowedMethods());
server.use(router.routes());
server.listen(port, (err) => {
if (err) throw err;
console.log(`Server ready on ${port}`);
});
});
I am trying to add a route to '/signup' in my express application. But, every time I am sending a post request to the server it is resolving in "No response". Whereas the '/' route is working. Where have I gone wrong with the code?
index.js
import dotenv from "dotenv";
import cors from "cors";
import morgan from "morgan";
import dbConnect from "./config/dbConnect.js";
import { authRoute } from "./routes/auth.js";
dotenv.config();
const port = process.env.PORT;
const DATABASE_URI = process.env.DATABASE_URI;
const app = express();
dbConnect();
app.get("/", (req, res) => {
res.sendStatus(200);
});
app.use(express.json());
app.use(cors());
app.use(morgan("combined"));
app.use("/api/v1", authRoute);
app.listen(port, () => {
console.log(`Server running at ${port}...`);
});
auth.js
import { Router } from "express";
const router = Router();
router.post("signup", (req, res) => {
const password = req.body.password;
console.log(password);
});
export { router as authRoute };
dbConnect.js
import mongoose from "mongoose";
import dotenv from "dotenv";
dotenv.config();
const DATABASE_URI = process.env.DATABASE_URI;
const dbConnect = () => {
mongoose.set("strictQuery", false);
mongoose
.connect(DATABASE_URI)
.then(() => {
console.log("connected");
})
.catch((error) => {
console.error(error);
});
};
export default dbConnect;
router.post("signup", (req, res) => {
const password = req.body.password;
console.log(password);
});
The client doesn't get a response because you haven't written any code to send a response.
You completely ignore the object passed to res.
You don't call res.json or res.render or res.send or any of the other methods that would send a response.
Seems like the problem was with my VSCode extension RapidApi client, tried using insomnia and it worked out fine. Sorry for the trouble!
I want to send data from my backend side with nodejs to my frontend side when I use fetch in the frontend side, I use reactjs.
and I get an error of "SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON" in the fetch function in useEffect function.
import { useEffect, useState } from "react";
import Item from "./item";
import style from "./show-item.module.css";
const ShowItem = (props) => {
const [orders, setOrders] = useState([]);
useEffect(() => {
fetch("/")
.then((res) => {
if(res.ok){
console.log('ok')
return res.json()
}
}).then(result => console.log(result))
.catch((err) => console.log(err));
}, []);
return (
<ul className={style["ul-item"]}>
{orders.map((item) => (
<Item
key={item.id}
id={item.id}
name={item.name}
detail={item.detail}
price={item.price}
amount={1}
/>
))}
</ul>
);
};
export default ShowItem;
I used in proxy in my react js app in package.json
"proxy": "http://localhost:5000",
this is my backend code
const adminRouts = require('./routes/admin');
const shopRouts = require('./routes/shop');
const shefRouts = require('./routes/chef');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 5000;
app.use('/admin',adminRouts);
app.use('/shef', shefRouts);
app.use(shopRouts);
console.log('listen ', port)
app.listen(port);
my shaf code
const express = require("express");
const router = express.Router();
const order = [
{
id: 1,
name: "הלחם שלנו",
detail: "לחם פראנה באפייה מסורתית,שמן זית ומטבלים טעימים",
price: 26,
},
];
router.use("/", (req, res, next) => {
console.log('here');
res.json(order);
});
module.exports = router;
HTML Is being returned, Signifying the wrong API route being called
First of all, it is worth noting that the backend is responding with HTML. Why is that? If you check in your express code there is no route where HTML is sent. The URL that you are using the fetch is '/'. This '/' route will get the base URL of 'localhost:5000' and nothing else. It seems that you are doing a request to the same URL that React is hosted in. This means that you are doing a get request to the 'public/' folder in the react app, and it is returning the HTML in the default 'index.html' that react uses.
You will need to change either the react proxy or the base URL for the server. I recommend changing all the API routes to be appended to '/api'. So the '/shef' becomes '/api/shef'. To make it dynamic make an API router with endpoint '/api' and move '/shef' to the API router file.
Although there are many ways to do this, here is one way:
make a 'api.route.js' file in the '/routes' folder
const router = require("express").Router();
const shopRouts = require('./routes/shop');
const shefRouts = require('./routes/chef');
router.get("/", async (req, res, next) => {
res.send({ message: "Ok api is working 🚀" });
});
router.use('/admin',adminRouts);
router.use('/shef', shefRouts);
router.use('/shop', shopRouts);
module.exports = router;
shaf code
const apiRoutes = require('./routes/api');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json(), bodyParser.urlencoded({ extended: false }));
const port = process.env.PORT || 5000;
app.use('/api', apiRoutes);
console.log('listen ', port)
app.listen(port);
Then in your frontend:
The only line changed here is:
Use which ever method you like to get the base URL. You might want to keep it in a .env file.
fetch(window.location.origin + "/api/shef")
import { useEffect, useState } from "react";
import Item from "./item";
import style from "./show-item.module.css";
const ShowItem = (props) => {
const [orders, setOrders] = useState([]);
useEffect(() => {
fetch(window.location.origin + "/api/shef")
.then((res) => {
if(res.ok){
console.log('ok')
return res.json()
}
}).then(result => console.log(result))
.catch((err) => console.log(err));
}, []);
return (
<ul className={style["ul-item"]}>
{orders.map((item) => (
<Item
key={item.id}
id={item.id}
name={item.name}
detail={item.detail}
price={item.price}
amount={1}
/>
))}
</ul>
);
};
export default ShowItem;
socket.request.user from isLoggedInSocket is undefined. For the client, I have also tried connecting with ws://127.0.0.1:5000. I am using Google oauth2 for passport js. My express endpoints successfully have the user session details. Once I comment out isLoggedInSocket, I can connect to the socket.
Does anyone have any insight on what I can do to get the session onto socket.io?
Server:
import express, { Application } from 'express';
import http from 'http';
import { Server } from 'socket.io';
import passport from 'passport';
import cookieSesson from 'cookie-session';
import cors from 'cors';
import fishingSocket from './sockets/fishing';
import authRouter from './routers/authentication';
import setupAuth from './authSetup';
import { isLoggedIn, isLoggedInSocket } from './middleware';
const corsConfig: any = {
cors: {
origin: ['http://127.0.0.1:3000'],
credentials: true,
},
};
const app: Application = express();
app.use(
cors({
origin: ['http://127.0.0.1:3000'],
credentials: true,
})
);
const session = cookieSesson({
name: 'pond-session',
keys: ['key1', 'key2'],
});
app.use(session);
app.use(passport.initialize());
app.use(passport.session());
setupAuth();
const server = http.createServer(app);
const io = new Server(server, corsConfig);
const wrap = (middleware: any) => (socket: any, next: any) =>
middleware(socket.request, {}, next);
io.use(wrap(session));
io.use(wrap(passport.initialize()));
io.use(wrap(passport.session()));
const isLoggedInSocket = (socket: any, next: any) => {
if (socket.request.user) {
next();
} else {
console.log('No auth in socket');
next(new Error('unauthorized'));
}
};
io.use(isLoggedInSocket);
fishingSocket(io);
app.use('/auth', authRouter);
server.listen(5000, () => console.log('Server Running'));
Client:
socket = io('http://127.0.0.1:5000', {
withCredentials: true
})
I make simple instagram api application and I have problem with my routes, export and import. i get error TypeError: Router.use() requires a middleware function but got a undefined
at Function.use (C:\Documents\Desktop\digi.me\node_modules\express\lib\router\index.js:458:13)
at Object. (C:\Documents\Desktop\digi.me\lib\routes\routes.js:12:8)
I have two routes userRouter that go on localhost:3000
and mediaRouter that go on localhost:3000/media
my userRouter.ts
import request, { post } from "request"
import express from "express"
import { Router } from 'express';
const app = express()
const token: any = process.env.INSTAGRAM_TOKEN
export const userRouter = Router()
userRouter.get("/", (req: any, res: any) => {
const url = 'https://graph.instagram.com/17841403377847296/?access_token='+token+'&fields=account_type,media_count,username'
request({ url: url, json: true }, (error: string, response: any) => {
if(error){
res.send("unable to connect to service")
}else{
res.send("USER " + response.body.username + " HAVE " + response.body.media_count + " POSTS")
}
})
})
my mediaRouter
import request, { post } from "request"
import express from "express"
import {Post} from "../models/Post"
import { Router } from 'express';
const token: any = process.env.INSTAGRAM_TOKEN
export const mediaRouter = Router()
mediaRouter.get("/media", (req: any, res: any) => {
console.log(0);
const url = 'https://graph.instagram.com/17841403377847296/media?fields=id,media_url,timestamp&access_token='+token+''
request({ url: url, json: true }, (error:string, response: any) => {
if(error){
console.log('error');
res.send("unable to connect to service")
} else {
const array = response.body.data
var Posts: Post[] = [];
array.forEach(function (obj: any) {
Posts.push(new Post(obj.media_url, obj.timestamp))
});
res.send(Posts);
}
})
})
my routes.ts
import { Router } from 'express';
import userRouter from "./routes"
import mediaRouter from "./routes"
import express from 'express';
const app = express();
const routes = Router();
routes.use('/', userRouter);
routes.use('/media', mediaRouter);
export default routes
and my main app.ts
import express from "express"
import * as dotenv from "dotenv"
import routes from "./routes/routes"
const app = express()
dotenv.config();
//envirements variable for port
const port: any = process.env.PORT
app.use(routes);
app.use(express.json());
//Adding server to port
app.listen(port, () => {
console.log("server is listen on port 3000")
})