Store Cookies at the client side using nodejs - node.js

there I am trying to store cookies using the post method using nodejs, cookies are not stored on the browser end currently node server is running on localhost 3001 and react server is running on port 3000
the code what I have written mentioned below
Can anybody please suggest me to fix the issue
const express = require("express")
const app= express()
const cookieParser = require('cookie-parser');
const cors = require("cors")
const port = process.env.port || 3001
app.use(cors())
app.use(express.json())
app.post("/names",async(req, res)=>{
console.log("Ho")
res.cookie("auth","nagendran")
res.json({msg:"Hello"})
})

Edit: Looks like cross origin requests needs quite some work to get cookies right. Take a look here.
Set cookies for cross origin requests

Related

Why there is a need to create a server in NodeJS application?

Learning Nodejs for my personal projects. Analysing other developers code examples, watching youtube videos. I noticed one thing that I don't understand completely, why most of nodejs examples I come across have a code part for http server initiation and port listening? But application itself not using any http related things like processing http requests/responses. For example:
const express = require('express')
const path = require('path')
const http = require('http')
const cors = require('cors')
const PORT = process.env.PORT || 5000
const app = express();
const server = http.createServer(app).listen(PORT, () => console.log(`Listening on ${PORT}\n`))
app.use(express.static(path.join(__dirname, 'public')))
app.use(cors({ credentials: true, origin: '*' }))
If my nodejs application is a script that needs to be run on server side that collects some information from other API's and stores in a database, etc., do I need to create and start HTTP server anyway?
why most of nodejs examples I come across have a code part for http server initiation and port listening?
Because that's how people use nodejs most of the time: as a web server. Which doesn't mean it is mandatory or even a good practice.
do I need to create and start HTTP server anyway?
Of course not. Why would you do that if you don't need it? Do not worry about tutorials or examples, these don't know about your case and your needs.

http2 in node.js, express, socket.io client

I am building a web app that uses a express and node.js in the backend. In my server.js file, I have the following code
const express = require("express");
const app = express();
const server = require("http").Server(app);
const io = require("socket.io")(server);
I recently discovered that there is http2 available, should I change the line 3 to
const server = require("http2").Server(app); instead?
If I switch to http2, is there anything else I need to specifically change that wasn't present in http1? And is the way of sending HTTP requests such as get or post any different from http1 to http2?
HTTP2 is more efficient and loads faster pages-Differences.
But I suggest you use https since its more secure and most of the browsers mark non https requests as insecure.
similar stack

net::ERR_SSL_PROTOCOL_ERROR on http POST to express server

I'm trying to post from a react client to an express server on localhost and I get this error in google chrome.
react app: http://localhost:3000
express app: http://localhost:5000
POST https://localhost:5000/upload net::ERR_SSL_PROTOCOL_ERROR
I don't have any SSL https self signed certificate, but do I need to? I have used create-react-app inside a directory within my express application to bootstrap my front-end so I'm unaware if maybe a webpack setting somewhere is trying to handle http as https for this particular operation?
I haven't used any bootstrapping for my express js application and I'll include my server file below for reference.
const express = require ('express')
const bodyParser = require ('body-parser')
const port = 5000
var app = express()
var cors = require("cors");
app.use(cors())
app.use(bodyParser())
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.post('/upload', (req,res)=>{
if (req.files === null ){
return res.status(400).json({message: 'no image uploaded please try again'})
}else{
const file = req.files.file
let body = req.body
res.json({body})
}
})
I know there are a fair few questions on this issue but they weren't relevant or didn't provide me any insight. I have tried making sure the ports are allowed through my firewall aswell. I have also cleared my browser cache.
I had the same issue and changed the URL to http://localhost:5000/upload instead of using https://localhost:5000/upload.
This has been discussed in multiple posts
By default you cannot call localhost request on browsers but you can disable the security
Check here : Disable same origin policy in Chrome
I also faced the same issue and I changed the URL to http://localhost:5000/path instead of using https://localhost:5000/path
It works for me.
I had the same issue but it was with WAGMI (react hooks for web3 dev) and instead of using "https://localhost:6969" (this was the RPC url for my local node) I used "http://localhost:6969" which worked!

After using DOTENV, server stops working in express generated by express generator

After including DOTENV the server stops working in express generated by express generator.
Here is how I include DOENV in app.js:-
require('dotenv').config({ path: 'variables.env' });
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var mongoose = require('mongoose');
This is the error message I receive in the browser when I try to access a route:
This site can’t be reached
localhost refused to connect.
Search Google for localhost 3000 parties add
ERR_CONNECTION_REFUSED
But if I remove this code:-
require('dotenv').config({ path: 'variables.env' });
It starts to work again.
I know you can't post your .env file here as it likely has secrets in it (the whole point of a .env), but Likely one or more of the variables in it are wrong. Check to make sure you're not changing the PORT variable and that all your other connection related variables (e.g. Use of https, database URL and credentials, etc) are set to the correct value.
Also ensure that the path you've configured for your .env file is correct.

Unable to understand the Express server concept using Node.js

I was referring to some online tutorials for establishing a Node server using Express 4. I will make my question very simple and easy to understand.
The main app.js file has the following lines (other code lines like middlewares etc. are not show here)
var express = require('express');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use('/', routes);
app.use('/users', users);
I have tested the above code. Included the index.js and users.js inside the routes folder. This worked perfect. This means that the http server is already created.
But, my confusion raised, when I say another type of coding done in another site. It has the following lines of code.
var express = require('express'),
routes = require('./routes'),
http =require('http’);
var app = express();
My first confusion is, why do we need to use the http middleware.
The code further creates a server like this
var server = http.createServer(app);
Since, I am using the Express framework, why do we need to create the server, this way
Reference can be found here https://github.com/azat-co/practicalnode/blob/master/ch5/blog-express/app.js#L72
Any help would be highly appreciated. Thanks in advance.
Perhaps the developer wanted to create a raw http server for some other specific use later on? Strictly speaking, it is not necessary to do that.
The following is perfectly sufficient to create an http server and begin listening for connections using express:
var express = require('express');
app = express();
app.listen(3000);
in express best way is:
app = express();
app.listen(3000);
in theory this:
var server = http.createServer(app);
could be used to reuse http server, for example to run sockets.
But app.listen also return http server like http.createServer(app);
We can do:
var server = http.createServer(app);
var io = require('socket.io')(server);
But we also can:
var server = app.listen(3033);
var io = require('socket.io')(server);
When createServer(app) may be useful? if we want listen to http i https:
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

Resources