I have created a elasticache redis cluster in aws.
Now I have endpoint(url + port)
Url looks "myredis.abc.xyz.cache.amazonaws.com" and port 6379
Now I want to store Key:Value pair in it, like we store in native Redis (redis.set, redis.get)
How to write nodejs code for it, I don't know. I searched a lot but didn't find any right resource.
Anyone can help me in this?
I tried following code but didn't work
ElastiCacheClient,
AddTagsToResourceCommand,
} = require("#aws-sdk/client-elasticache");
const conf = {
host: "myredis.abc.xyz.cache.amazonaws.com",
port: 6379,
region: "us-east-1",
};
const client = new ElastiCacheClient(conf);
const param = { manoj: "kumawat" };
const command = new AddTagsToResourceCommand(param);
const data = await client.send(command);
console.log(data);
Related
I am new in MongoDB, all my life I used MySQL.
I have created an account in atlas, set the IP to my IP and created a user and saved the password.
here is my code, why doesn't it work?
app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoPractice = require('./mongo');
const app = express();
app.use(bodyParser.json());
app.post('/products', mongoPractice.createProduct);
app.get('/products');
app.listen(3000);
and the mongo.js:
const MongoClient = require("mongodb").MongoClient;
const url =
"mongodb+srv://idan:<85IwoSzeQssHMzLN>#cluster0.tpejv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const createProduct = async (req, res, next) => {
const newProduct = {
name: req.body.name,
price: req.body.price,
};
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db();
const result = db.collection("products").insertOne(newProduct);
} catch (error) {
return res.json(error);
}
client.close();
res.json(newProduct);
};
const getProducts = async (req, res, next) => {};
exports.createProduct = createProduct;
exports.getProducts = getProducts;
the POSTMAN output:
Your ip may have changed, (check if the current ip address has information "(includes your current IP address)". For testing(!) you can add address 0.0.0.0/0 to the whitelist - it means every ip will be accepted - this solution is good for beginners
Firstly check you connection link from mongodb connect
Check username, password again
You can change password and try again
In mongo.js
You need to remove "< >" around the password.
const url = "mongodb+srv://idan:**85IwoSzeQssHMzLN**#cluster0.tpejv.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
I encountered the same error once and I might have solution.
The most common one is that your IP address set to access the database might not match with your current IP address in which case you need to set it to your current IP or set to allow access from anywhere.
The issue which I had : If you have recently started using an ethernet cable try going back to wireless to access the mongoDB database from your backend script.
This is what im trying to create, This is all new to me. I hope someone can help me.
//this is the part I cannot figure out, maby anyone knows a tool how to find this port
const endpointUrl = "opc.tcp://145.49.49.3:???";
const opcua = require("node-opcua");
const AttributeIds = opcua.AttributeIds;
const OPCUAClient = opcua.OPCUAClient;
(async function main(){
const client = new OPCUAClient({});
await client.connect(endpointUrl);
const session = await client.createSession({userName: "admin", password: ""});
const dataValue = await session.read({nodeId: "ns=1;s=AcquisitionCount",attributeId: AttributeIds.Value});
console.log(`Count is ${dataValue.value.value.toPrecision(3)}°C.`);
await client.closeSession(session,true);
await client.disconnect();
})();
The default port is 4840, but you’re going to have to figure it out one way or another.
Normally the server you are connecting to has the full endpoint URL, port included, documented or listed in some configuration somewhere.
I need to access my backend API to send info from a contact form for an email, I deployed my app in a webhost called Kinghost and it gave me two urls the first is generically mywebaddr.com:port-number and the second is mywebaddr.com/site.
I have tried to use both addresses with the function route in the end just like I did in localhost, that in order to work I used http://localhost:4000/contact for example, but it didn't work...
this is my request:
const baseUrl = 'http://mywebsiteurl.com/contact'
const initialState = {
message: {
name: '',
email: '',
subject: '',
main: ''
},
}
export default class ContactUs extends Component {
state = { ...initialState }
reset = () =>{
this.setState({message: initialState.message})
}
send = () => {
const message = this.state.message
const url = baseUrl
console.log(message)
axios.post(url, message)
.then(this.reset())
.then(alert('Message successfully sent!'))
}
this is my index.js (backend)
const express = require('express')
const app = express()
const consign = require('consign')
const port = 4005
consign()
.then('./config/middlewares.js')
.then('./api')
.then('./config/routes.js')
.into(app)
app.listen(port, () => {
console.log(port)
})
my middlewares.js contains cors
const bodyParser = require('body-parser')
const cors = require('cors')
module.exports = app => {
app.use(bodyParser.json())
app.use(cors())
}
Actually, I don't think it's because of my code itself once I can execute everything perfectly in localhost, but somehow I can't get through with the correct URL
I'm new to node and I can't guess what am I doing wrongly, so if someone can help me I'd be really thankful :)
This is not a question for stack-overflow as your issue is not with the application but is with your network.
Anyhow, your API application is running on port 4005. Make sure the port is open with your hosting provider. while your at it make sure your port 4000 is open as well.
after you confirm your firewall settings ill update my answer if your still facing issues.
I use Helmet with Express to set quite some security HTTP headers from the server side. This is nicely done, when rendering client pages on top of the node.js app, using:
var app = express();
app.use(helmet());
..
res.render("pages/index", data);
All the resources on the index page will have the Helmet headers. Unfortunately, socket.io does its own header management. So, anything that comes after /socket.io/ will have insecure/its own headers. For example here:
<https_path>/socket.io/socket.io.js
<https_path>/socket.io/?EIO=3&transport=polling&t=Lj4CFnj&sid=ILskOFWbHUaU6grTAAAA
Hence, I want to set custom headers for all socket.io items manually.
This is how I require socket.io (excerpt only):
/src/app.js
var express = require("express");
var sio = require("socket.io");
var app = express();
var io = require("./../lib/io.js").initialize(app.listen(REST_PORT, () => {
logger.info("Application ready on port " + REST_PORT + " . Environment: " + NODE_ENV);
}));
/lib/io.js
exports = module.exports = {};
var sio = require("socket.io");
exports.initialize = function(server) {
var options = {
cookie: false,
extraHeaders: {
"X-Custom-Header-For-My-Project": "Custom stuff",
}
};
io = sio(server, options);
io.on("connection", function(socket) {
// logic
)};
The "extraHeaders" option doesn´t work, I guess it could only with socket.io-client. I did large amount of googling around, but not luck on this.
Also looked around how to use socket.request (apparently it helps with headers, according to: here), but I couldn´t figure that out either.
Could you guys help?
extraHeaders options will work as below, as you need to remove "transports: ['polling']," in case you are using, and use below pattern. This worked for me, and was able to send custom headers.
package used :- "socket.io-client": "^2.2.0",
this.socket = io(environment.host, {
path: `/api/backend/socket.io`,
origins: '*:*',
// transports: ['polling'],
transportOptions: {
polling: {
extraHeaders: {
'authorization': token,
'user-id' : userId
}
}
}
})
Ref:- https://socket.io/docs/client-api/#With-extraHeaders
I’m working with the Node.js server and using the Socket.io to manage connections by Socket but I’m having a problem with the SSL certificate.
Lot of users can access the Node.js server normally, but others users doesn’t access and they receive this error:
When I set my server I have this SSL options:
var privateKey = fs.readFileSync('/root/cert/key.key', 'utf8').toString();
var certificate = fs.readFileSync('/root/cert/cert.crt', 'utf8').toString();
var ca = fs.readFileSync('/root/cert/ca.crt').toString();
var credentials = { key: privateKey, cert: certificate, ca: ca };
var app = express();
var httpsServer = https.createServer(credentials, app);
var io = require('socket.io')(httpsServer);
Somebody knows how to resolve this error? The problem is only some users receive this error.
Well, as far as I can see, you are missing a listening port for you https server.
var httpsServer = https.createServer(credentials, app).listen(<port>);
I had so much trouble with ERR_SSL_PROTOCOL_ERROR that I have to give you my solution
NodeJS server 16.15.0 with "socket.io": "2.4.1" (I assume it works with other NodeJS versions)
const path = require("path");
const fs = require("fs");
const io = require("socket.io")();
const folder = path.join(__dirname, "ssl");
const privateKey = fs.readFileSync(path.join(folder, "server_key.pem"), "utf8");
const certificate = fs.readFileSync(path.join(folder, "server_cert.pem"), "utf8");
const optSsl = {
key: privateKey,
cert: certificate,
ca: [certificate],
requestCert: false, // put true if you want a client certificate, tested and it works
rejectUnauthorized: false,
};
const server = require("https");
const webServer = server.createServer(optSsl);
webServer.listen(8025); // port number
io.listen(webServer);
io.on("connection", (client) => {
/*...*/
});
/*...*/
Angular 10.2.7 with "ngx-socket-io": "3.2.0" (I assume it works also with other Angular versions)
import { Socket, SocketIoConfig } from 'ngx-socket-io';
/*...*/
socket: Socket;
socketConfig: SocketIoConfig;
socketConfig = {
url: "https://myserver:8025",
options: {},
};
socket = new Socket(socketConfig);
socket.connect();
Looks like your apache2 is not properly configured.
Check if you have your config file enabled:
a2ensite default-ssl
And then restart the server.