Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a static xml file from nodejs server

I am integrating a 3rd party template which has a slideshow written using Mootools. The nodejs is configured with express and ejs

The data for the slideshow comes from a few xml files. For example data.xml. I placed the data.xml in public folder and added the following code to server.js (the main file)

app.use(express.static(__dirname + '/public'));

app.post('/data.xml', function(req, res){
    res.contentType('application/xml');
    res.sendFile('/data.xml');
});

Unfortunately this does not seems to work. I can see the file if I type the url http://localhost:8080/data.xml

But the response I see in firebug is " Cannot POST /data.xml "

I am assuming Mootools is trying to access the file using some POST method. Any suggestions for this problem?

like image 926
phpkode Avatar asked Feb 04 '16 08:02

phpkode


People also ask

How do I serve a static file in node JS?

In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. After installing node-static module, you can create static file server in Node.

How do you access XML elements in node JS?

Node. js has no inbuilt library to read XML. The popular module xml2js can be used to read XML. The installed module exposes the Parser object, which is then used to read XML.

How do I serve a directory in node JS?

Here is an example of a script that will serve the files in the current directory: var fs = require('fs'), http = require('http'); http. createServer(function (req, res) { fs. readFile(__dirname + req.


1 Answers

when you are sending the file with sendFile() you need to point to the absolute address check this. note that I have the data.xml in the main folder.

you can access the file with localhost:8080/data (not localhost:8080/data.xml) and also as this is a post, you cannot access it through browser. use postman instead. or if you need it to be accessible on browser you need to change the protocol to get.

var express = require('express');
var path = require('path');
var app = express();

// you don't need this line!
// app.use(express.static(path.join(__dirname)));


app.post('/data', function(req, res){
    res.contentType('application/xml');
    res.sendFile(path.join(__dirname , 'data.xml'));
});



var server = app.listen(8080, () => {
	console.log('Started listening on 8080');
});
like image 105
user3505838 Avatar answered Oct 26 '22 13:10

user3505838