i am having an xml file.I need to expose an api in such a way that it can consume xml files throughnodjs server api.
how can i receive a simple xml file in my nodejs server. i need a nodejs server script.
Try this code after struggling sometime I successfully get the code as per your need.
var express = require('express');
var fs=require('fs');
var app = express();
var conf;
var result;
app.get('/Excel', function(req, res){
result=fs.readFileSync('E:/User/nodejs/nodejs/tasks/result.xml');
res.end(result);
});
app.post('/posting',function(req,res){
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function (){
fs.writeFile('E:/User/nodejs/nodejs/tasks/result.xml', body, function() {
console.log(body);
res.end('Successfully Posted');
});
});
});
app.listen(3000);
console.log('Listening on port 3000');
After you run the server Post the data in content-type as application/xml using http://localhost:3000/posting and place your code in body and as result result.xml file will be created with the data.And you can get this file by http://localhost:3000/Excel.Hope this helps for you.
You can use a simple XML parser middleware such as express-xml-bodyparser. A working examples with express can be found in the above mentioned site.
Related
I am writing a server that is meant to serve and receive files. It is written in node.js, using express.js. I also have a client, also written in node, which is meant to send a request to the server and receive the files on the server.
Server-side
const express = require("express");
const app = express();
const file = "./samplefiles/Helloworld.txt";
app.get("/", (res)=>{
res.download(file);
});
module.exports = app; //this exports to server.js
const http = require("http");
const app = require("./app.js);
const port = 8080;
const server = http.createServer(app);
server.listen(port, () => {
console.clear();
console.log("server running");
})
Client-side
const request = require("request");
request.get("http://localhost:8080/", (req, body) => {
console.log(body);
console.log(res);
});
If I try to access it by my browser I am asked what I want to do with the file, it works. However, Is I run my client-side code it prints the body and the res(being null). I expected the file name and it's content to be in the body but only the content of the file was in the body.
I want to receive the whole file, is possible, or at least get the name of it so that I can "make" a copy of it on the client-side.
Change code your server side to:
const port = 8080;
const express = require("express");
const app = express();
const path = require('path');
app.get("/", function(req, res){
res.sendFile(path.join(__dirname, 'app.js'));
});
app.listen(port, () => {
console.clear();
console.log("server running");
});
Change code your client-side to:
var request = require('request');
request('http://localhost:8080/', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print data of your file
});
You need to install request npm i request for client side
You can serve up any files you want with express static method:
app.use(express.static('public'))
in this case just put all the files you want to serve in folder called public and then you can access it by localhost:8080/Helloworld.txt.
I ended up working around it.
I sent the file name as a header and was thus able to create a replica of the file I wanted to download using the body info and the filenameheader.
I am new to node js.
I wrote a server using node js which will read the request data and save that data into an image file.(Because the data coming is image data itself.)
The node js script I wrote is :
const http = require('http');
const fs = require('fs');
const server = http.createServer();
server.on('request', function(request, respond) {
var body = '';
filePath = '1.jpg';
request.on('data', function(data) {
body += data;
});
request.on('end', function (){
fs.appendFile(filePath, body, function() {
respond.end();
});
});
});
server.listen(8080);
And from the terminal on same machine , I fired a curl command to send the image :
curl -X POST --data #tmp.jpg 127.0.0.1:8080
The tmp.jpg is opening perfectly on my machine.
But 1.jpg (created by node js) is not opening.
What can be the problem ?
Any help would be highly appreciated.
The issue lies with your usage of curl. To send binary data, use the --data-binary flag instead:
curl -X POST --data-binary #image.jpg 127.0.0.1:8080
Also, you need to use writeFile instead of appendFile. The latter will add each request's data to the same file, which wil not be readable as image.
Furthermore, when processing binary data I find it easier to use buffers instead of string. The request processing would look like this:
server.on('request', function(req, respond) {
filePath = '1.jpg';
var chunks = []
req.on('data', d => {
chunks.push(d)
})
req.on('end', function (){
var data = Buffer.concat(chunks)
fs.writeFile(filePath, data, function() {
respond.end();
});
});
});
I'm building a react app
In one component I'm writing this GET request which works:
In another component I'm writing this POST request:
Which then returns this 404 error:
And I have no idea how my GET works but my POST returns 404:not found when I'm requesting the same file both times?
UPDATE:
I'm running a node.js server now but it's a bit of a frankenstein's monster as this really isn't an area I have an understanding of. Does anyone know what I'm doing wrong?
// Server setup from node.js website
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// Trying to listen for data from React app to feed into JSON (broken)
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/scene-setup.json", function(request, response) {
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
});
app.listen(3001);
// Updating JSON file with "obj" (working)
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
Axios is used for making HTTP requests. So, you should have a backend server running that can handle these requests. I am not sure what exactly is the data that you want to save. If you need access to that data, should be saving it on the backend.
If you want to save some data just on the client side, HTML5 filesystem API might be something you want to look at. It can manage some data in the limited sandboxed part of user's filesystem.
I've managed to make a GET request to an API however now I want to get the response on to a Jade page.
Here is my code for the GET request so far. This is in 'index.js' in the routes 'folder'. Any ideas about how I can get the response on to a Jade page?
router.get('/', function(req, res) {
var url = 'http://data.police.uk/api/forces';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var response = JSON.parse(body)
console.log("Successful")
});
}).on('error', function(e){
console.log("Error: ", e);
})
});
module.exports = router;
In your router
res.render('viewName',{"variable":"value"});
In your view
p #{variable}
Instead of trying to start from scratch, you should probably look at some sample templates for node.js with express.
http://blog.ijasoneverett.com/2013/03/a-sample-app-with-node-js-express-and-mongodb-part-1/
This would tell you how to set up the structure of the app.
Here is my code:
var express = require('express'),
app = express.createServer(express.logger());
app.use(express.bodyParser());
app.get('/', function(request, response) {
var name = request.param('name', null);
response.header('Content-Type', 'text/event-stream');
var t = setInterval(function(){
response.write('Hello World by '+name+' (using http-1.1 streaming data!)<br />');
}, 2000);
/*request.socket.on('close', function() {
clearInterval(t);
}); */
});
var port = process.env.PORT || 5000;
app.listen(port, function() {
//clearInterval(t);
console.log("Listening on " + port);
});
I am using express because I am testing this in heroku and I used the guide there.
So when I open the app I get a download popup with the data in the file (downloaded) instead of the html (dom) response.
What did I do wrong? (is it a browser problem?)
Edit:
#Joe, has solved my initial problem but yet, I have two questions:
1) Why i don't need to insert a 'correct' content type? (of streaming?)
2) Why does this code out put only after along time (about half a minute).?
If you are trying to display it as HTML you will want your Content-Type to be text/html