I Have the following code:
...
var servceStatic = require("serve-static");
var app = express();
app.use(express.compress());
app.use(servceStatic('static'));
...
Somehow it manages to serve all kind of files except those that end with ".json". Why is this?
you don´t need this module serve-static, because it is build in in express:
create a public folder and than just add this line to your code after your instantiation of express:
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
This should hand out all your files including the JSON files.
serve-static#index: By default this module will send “index.html”
files in response to a request on a directory. To disable this set
false or to supply a new index pass a string or an array in preferred
order.
var path = require('path');
app.use(express.static(path.join(__dirname, 'public', {
'index': ['index.json', 'index.html', 'index.htm'],
}));
Related
I have express api with json data file, every time I do test for api routes (with super test) it overwrite data, one of the solutions is to create a sepreate json file just to test.
controllers has routes for CRUD api methods and each route calling Object module to retrive data from db.json file
API running on localhost:3000
API test running on localhost: 4000
in my route I need to pass the path= req.get('host') as module which has the following:
const fs = require("fs");
const fileDataPath = "./data.json"
const testFilePath = "./testData.json"
const saveData = (data) => {
const stringifyData = JSON.stringify(data, null, 2)
fs.writeFileSync(fileDataPath, stringifyData)
}
const getEntryData = () => {
const jsonData = fs.readFileSync(fileDataPath, "utf-8")
return JSON.parse(jsonData)
}
if I do modules. exports = path
and then in module when I'm imorting it again I'm getting the following erorr
"Accessing non-existent property 'path' of module exports inside circular dependency"
and path undifined
How I can do supertest for my api without effecting my json data file?
I'm working in MySQL Database class. In React Project, I can instantiate a File([Blob],filename). But in the Express Backend project, I can't use File module. It show an error as ReferenceError: File is not defined. I don't know how to use them without importing like the React project.
Here is my code for instantiating the File() Object. I tried to import it from "buffer"
downloadProfile = (id,success) => {
this.db.query(`SELECT pi.Filename, pi.Data AS Buffer, pi.MIME, pd.Data FROM profile_image AS pi JOIN profile_data AS pd ON pi.UserID = pd.UserID WHERE pi.UserID = ? AND pd.UserID = ?`,
[id,id],(err,result)=>{
if (err) throw err
const filename = result[0]["Filename"]
const buffer = result[0]["Buffer"]
const mime = result[0]["MIME"]
const image = this.getImageBase64(buffer,mime)
const imageBlob = new Blob([buffer],{type:mime})
const iamgeFile = new File([imageBlob],filename,{type:mime})
const data = JSON.parse(result[0]["Data"])
success({["Data"]:data,["Image"]:image})
})
}
In addition, which one between CommonJS and Module that recommend to working with Node.js Express project.
I need to upload bulk rows of data using Firebase console's 'Import JSON' utility. But I could not get a way to enable Auto Generated Keys like -Kop90... for each rows. But instead it created 0,1.. keys.
This is my sample data
[
{"date":1448323200,"description":"test data1","amount":1273},
{"date":1448323200,"description":"25mm pipes","amount":2662}
]
I would like to generate something like this
I had a similar problem to yours,
I ended up finding a nice solution for the firestore using JS & Node: https://www.youtube.com/watch?v=Qg2_VFFcAI8&ab_channel=RetroPortalStudio
But since I needed it for the Realtime Database I just altered it slightly to suit my needs:
Pre-requisites:
JS SDK installation: https://firebase.google.com/docs/web/setup?authuser=0#add-sdk-and-initialize
Using SDK version 8 (namespaced) [Could be easily altered for use in v9]
Steps:
Create folder called files in root project directory:
Add all your json files as shown below:
Add the following code to a file (in this example the file is called "uploader.js"):
NOTE: The only thing missing from the below code is the firebaseConfig obj, you can get this obj by following this guide: https://support.google.com/firebase/answer/7015592#zippy=%2Cin-this-article
var firebase = require("firebase/app");
require("firebase/database");
const firebaseConfig = {
// your config details...
};
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
// File directory details:
const path = require("path");
const fs = require("fs");
const directoryPath = path.join(__dirname, "files");
fs.readdir(directoryPath, function(err, files) {
if (err) {
return console.log("Unable to scan directory: " + err);
}
files.forEach(function(file) {
var lastDotIndex = file.lastIndexOf(".");
var items = require("./files/" + file);
var listRef = database.ref(`${file.substring(0, lastDotIndex)}/`);
items.forEach(function(obj) {
var postRef = listRef.push();
postRef.set(obj)
.then(function(docRef) {
console.log("Document written");
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
});
});
});
Lastly, open the terminal to the directory where uploader.js can be found & run:
node uploader.js
After the running the operation, each file becomes a collection, and all the contents of each file are listed with a unique pushId:
I have an express server that handles json payloads (using body-parser). It's a pretty standard setup:
const app = express();
...
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
...
app.post('/api/v1/login', usersController.login);
...etc
But now I have one query - a hook from an outside service - that's submitting data to me as multipart/formdata. How do I deal with those? Do I have to rejigger my entire setup?
Thanks.
I use connect-multiparty package.
An option could be like this (more specific):
var multipart = require('connect-multiparty');
app.post('/api/v1/login', multipart(), function(req, resp) {
console.log(req.files); // in req.files are the files
});
Or just:
var multipart = require('connect-multiparty');
app.use(multipart());
My site is running on Node and using the Express framework.
My goal is to gather data from the Yahoo Placefinder api. It does not support JSONP, so I need to send my JQuery.getJSON request to my own proxy. My proxy would then send an http request to the Placefinder api, and echo the response.
If I were using php instead of Node, I would just make a new php file that includes a curl request to the placefinder api and echo the response.
But, I am using Node and I'm not sure where to start.
And, I'm using the Express framework.
My Questions are:
Where would the proxy fit within the Express framework? The public folder?
Where can I find some info on how to code a proxy in Node?
Will I need to modify the configuration of my Rackspace cloud (ubuntu) server in order for this to be possible?
See node-http-proxy. It should be better than implementing your own proxy.
Express lets you add middlewares as arguments when you do express.createServer(). Or, you can add them afterwards by using .use(proxy).
I don't think so.
To give an example (untested code):
var httpProxy = require('http-proxy'), express = require('express');
var yahooProxy = httpProxy.createServer(80, 'yahoo.com');
var app = express.createServer();
app.configure(function () {
app.use('/yahoo', yahooProxy);
});
...
Here's another example with 1.0.X that demonstrates header injection.
var express = require( 'express' );
var proxy = require( 'http-proxy' ).createProxyServer;
var app = express();
app.configure(function() {
// Inject some request headers here before we proxy...
app.use( function( req, res, next ) {
req.headers[ 'x-my-header' ] = 'blah blah';
next();
});
// Proxy based on path...
app.use( '/stack', proxy({ target: 'http://stackoverflow.com'} ).web );
app.use( '/yahoo', proxy({ target: 'http://yahoo.com'} ).web );
app.use( function( req, res ) {
res.send({ ok: false, message: 'Not much here.' })
});
}).listen( 3000 );
You can just add another route to your express app, perhaps at /api/yahoo/....
This view function will then make a call to the Yahoo API, probably using: http://nodejs.org/docs/v0.4.9/api/http.html#http.request, and then when that request finishes you simple return the result as JSON.
However, keep in mind that your proxy is public and that anyone can make requests through it. I would suggest some basic authorization. A generated value which you provide to the page making the request should work.
Using http-proxy 1.0 with express:
var httpProxy = require('http-proxy');
var apiProxy = httProxy.createProxyServer();
app.get("/api/*", function(req, res){
apiProxy.web(req, res, { target: 'http://google.com:80' });
});
Nowadays this seems to be the easiest solution to add a proxy to Express:
https://www.npmjs.org/package/proxy-middleware