I have a localhost 1337 server and a 3000 server
1337 The server is sending data.
3000 The server is the receiving place.
1337 Send the data from the server
I want to get it from the 3000 server
It's the 1337 source first.
router.get('/send', function (req, res, next) {
var params = req.query; //post일때 사용
console.log(params);
// res.status(200).send({input:params});
request('http://localhost:3000/', function (error, response, body) {
console.log("#########################");
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', params);
});
});
Here we go to the 3000 server.
My data is also recorded in the LOG
But I do not think I'm going to log in, connect to the 3000 server, and send the data.
And 3000 server source.
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
var params = req.query;
console.log("333333333333333333333333333333333333333333");
console.log(params);
});
TITLE on the 3000 server and 33333333333 on the CONSOLE.LOG
I want to receive data from 1337!
Let me know the right way.
I'm also a beginner in Node, so this might not be the correct/most efficient way to do this. However, I've managed to connect a local webapp to a local Node server and pass data using Express, like so:
// server.js
var express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(cors());
var port = process.env.PORT || 3000;
http.createServer(app).listen(port, function (err) {
con.connect(function() {
console.log("Listening in port " + port);
});
});
This sets the server up for listening to requests, and now you can do something to specific requests, like:
app.post('/users', function(req,res) {
//Do something when receiving a POST request in "https://localhost:3000/users", like...
console.log(req.body); //... print the request content
});
Then all you have to do is send a request via GET/POST on your local server, and it should work.
Here is Express documentation, explaining some of the stuff it can do:
http://expressjs.com/en/api.html
Hope this helps!
Related
I want to be able to send some kind of progress data from a long running async function running on a node express server when a client requests for the data and waits for its completion.
const express = require('express');
const app = express();
const port = process.env.PORT;
app.get('/', (req, res) => {
// Send data to client
(async () => {
await someFunc();
})();
})
Assuming someFunc() is responsible to return the progress data and the final response to the client.
Well, you can't do that since the first response will end the HTTP request (end the connection).
What you looking for is WebSocket, with WebSocket you can keep pushing data to the client since it maintains the connection
check https://www.npmjs.com/package/websocket
I have a node.js application which I use to interact with a REST API provided by another server. I would like to expose a web interface (html + css + javascript) using express.js in order to control the first application.
How can I let the browser talk to the server and let it make node.js actions like using http from that machine or writing to its filesystem? I tried using XMLHttpRequest, but HTTP requests are sent by my local PC instead of from my server.
The only solution I found is using XMLHttpRequest in the javascript of my web interface to invoke some middleware functions on my server, but I had some problems: when I make POST requests, I cannot read data from server. I used FormData and its append method to make the "body" of the POST request, then used body-parser in express to read that body, but it turns out to be always empty. Also tried changing the 'Content-Type' of the header.
Any suggestions? Any better solution than mine (I think it is not efficient)?
As pointed by Jonas, using node server as proxy would be the right approach.
I'm providing sample code for both frontend as well as backend app. Hope this helps you.
Frontend App Code
<html>
<head>
<script type="text/javascript">
function sendData(data) {
if (!data) {
// lets define some dummy data for testing
data = { somekey: "somevalue", anotherkey: "anothervalues" };
}
var XHR = new XMLHttpRequest();
var FD = new FormData();
// Push our data into our FormData object
for (name in data) {
FD.append(name, data[name]);
}
// Define what happens on successful data submission
XHR.addEventListener("load", function(event) {
alert("Yeah! Data sent and response loaded.");
alert(event.target.responseText);
});
// Define what happens in case of error
XHR.addEventListener("error", function(event) {
alert("Oops! Something went wrong.");
});
// Set up our request
XHR.open("POST", "http://path/to/your/nodejs/server/app");
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
</script>
</head>
<body>
<button onclick="sendData()">Send Test Request to the Server</button>
</body>
</html>
Backend App code
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => res.send('Yeah! Server is UP! Post some data'));
app.post('/', (req, res) => {
// You'll see the posted data in req.body, simply for testing purpose return it back to the calling user
res.json(req.body || {});
});
const server = http.createServer(app);
server.listen(3000);
server.on('error', console.error);
server.on('listening', () => console.log('Listening on 3000'));
process.on('exit', (code) => console.warn('Server terminated with code=' + code));
Please note that for this backend app to run, you must have installed following npm packages: express, body-parser
I'm using node.js and JQuery to communicate. Whenever I send a post request to my node.js express server, it receives the request but does not seem to give a response.
Client code:
$("#submitdetails").click(function(){
$.post("http://neztorian.xyz:26/",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
Sever code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
console.log("Running");
app.post('/', function (req, res) {
console.log(req.body);
res.send("recieved");
})
app.listen(26);
The server receives the post request and logs it to console but the alert message does not appear on the client. Thank you for your help. Sorry if this is a stupid question.
Edit: Thank you for your answers. Problem was: Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://neztorian.xyz:26' is therefore not allowed access. I've fixed the issue by adding that header to the server.
The request is not allowed by the browser because the server is not sending the Access-Control-Allow-Origin header.
Set the header and request are allowed.
app.post('/', function (req, res) {
console.log(req.body);
res.header('Access-Control-Allow-Origin', 'http://neztorian.xyz:26');
res.send("recieved");
});
Read more here: CORS
I have a simple nodeJs server with express and I have an external module that handles sending the response to the requests. In order for this file to work, it needs to access express res variable. Before, I used to send this variable to the module functions to use it, but then I tried to use a middleware to store this variable in the module and not send it every time I'm calling a function, and it worked!
This is the code:
// app.js
var http = require('http');
var express = require('express');
var app = express();
var response = require('./response.js');
// store the value of 'res' in the response module
app.use(function(req, res, next) {
response.setRes(res);
next();
});
app.get("/", function(req, res){
response.success("Welcome"); // works fine
});
app.get("/images", function(req, res){
response.forbidded("Forbidded"); // works fine
});
var server = http.createServer(app);
server.listen(3000, function(){
console.log("listening... ");
});
and this is the other module
// response.js
exports.setRes = function(_res){
res = _res;
};
exports.success = function(msg){
res.status(200).send(msg);
};
exports.forbidded = function(msg){
res.status(403).send(msg);
};
My question is: Is this a good approach? and will this affect my application if the number of users increases (I'm worried that one user might get the res of another user)
Building a REST API with NodeJs and Express: my goal is to implement the 2 simplest Middlewares:
The first one is going to log the incoming request
The second one is going to log the processed response (which is a JSON)
The first middleware (in app.js)
function logReqMiddleware(req, res, next) {
log.info('>>> %s at %s', req.method, req.path);
next();
}
The second middleware (in app.js)
function logResponseMiddleware(req, res, next) {
log.info('<<< %s (%s)', JSON.stringify(res), res.status);
next();
}
The controller function (in apiController.js)
export var router = express.Router();
router.get('/', foo);
function foo(req, res, next) {
res.status(200).json({ stupidExample: true });
next();
}
Building the app (app.js)
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logReqMiddleware);
app.use('/api', apiController.router);
app.use(logResponseMiddleware);
var server = app.listen(3000, function(){ log.info('running'); });
Now, making a request at localhost:3000/api says: can't set headers after they are sent; this is the related super cool response my question is, is it incompatible to write json data with json() and adding the second middleware? How can I solve this?
Don't call next() inside logResponseMiddleware. There's nothing else to do, so calling next() is probably sending you into express's default 404 handler which is trying to respond with a default status and body.
Aside: JSON.stringify(res) is not what you want. res is an object instance representing the response (lots of methods, internal state properties, etc). It is not the response body content string. As the res is a writeable stream, it's not going to keep the response body content around for you to log, it's just going to try to send it over the HTTP connection.