I wanted to send code to some node application and I use the postman with post message and in the body I put the following:
module.exports = function() {
var express = require('express'),
app = express();
app.set('port', process.env.PORT || 3000);
return app;
}
in the header of the request I put
content-Type application/text/enriched
in the node code I use the following
module.exports = function (app) {
fs = require('fs');
var bodyParser = require('body-parser');
...
app.post('/bb',function(req,res){
var fileContent = req.body
and the file content is empty ,I was able to see that it works since it stops in debug
If you want to add a custom content type then you need to keep two things in mind:
Content type couldn't be "application/text/enriched", in other hand "application/text-enriched" is ok. Max two "words".
You must provide a custom accept header on body parser configuration BUT body parser return you a buffer when you use custom header
See the example:
var express = require('express')
var app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.raw({ type: 'application/text-enriched' }))
app.post('/demo', function(req, res) {
console.log('POST DATA')
console.log('STREAM', req.body)
console.log('STREAM to STRING', req.body.toString())
res.status(200).send('ok');
});
app.listen(3000);
You can test in your console with curl:
curl 'http://localhost:3000/demo' -d 'name=john&surname=doe' -H 'Content-Type: application/text-enriched'
I recommend you try to not use a custom content type header because things are easier. I hope that my explanation help you.
Related
I have an array that is initialized when my user makes an input. I want that array to be passed to the nodeJS side of things rather than just stick around in the frontend. All the other variables that I am grabbing are named "net[object]" so I can grab them all in an array when necessary. The array I created only ever has one element being displayed in an input group at a time. If you need a better visual, go to "#nodes in hidden layer" for the neural net demo here: http://irisml.org/demos/
I am a complete noob when it comes to web development, so please be patient with me :)
//JS code creating array
numLayers.addEventListener('input', function(){
nodesArray.length = 0
num = numLayers.value;
nodes.innerHTML = '';
initialized = true;
for(var i = 1; i < num - 1; i++){
var node = document.createElement("option");
var textnode = document.createTextNode("Nodes in Hidden Layer " + i);
node.appendChild(textnode);
document.getElementById("nodes").appendChild(node);
nodesArray.push(1)
}
});
//Current NodeJS code
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.post('/', function(req, res){
console.log(req.body.net)
});
You can use "fetch" to send a post request to the backend.
//frontend
let nodesArray = [1,2,3];
let body = JSON.stringify({net:nodesArray});
fetch("/",
{method:"post",
body:body,
headers: {
'Content-Type': 'application/json'
}});
Your backend needs to listen on a port
//backend
var express = require('express');
var app = new express();
app.use(express.json())
app.listen(3000, console.error); //listen on port http://localhost:3000
app.use('/static', express.static(__dirname + '/static')); //OPTIONAL host static/index.html
app.post('/', function(req, res){
console.log(req.body.net, 'net');
res.send("RESPONSE");
});
I'm new to REST api's and javascript in general and I'm having trouble using GET to retrieve a json file and display it in a browser. I'm only running my api as a localhost for now. I can get my server running but just can't get my json file to display. Below is my code, I have tried different things with the responce but have had no luck with getting it to work. Everything I've tried with it has displayed errors. Both this file and the json file are in the same folder. If someone knows what I need to put for instead of the //responce() it would be greatly appreciated. Thanks!
var http = require('http');
var express = require('express');
var app = express();
var port = process.env.port || 3000;
app.listen(port, function(){
var datetime = new Date();
var message = "Server running on Port:- " + port + " Started at :- " +
datetime;
console.log(message);
});
app.get("/userget", function(request, responce){
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('database.json', 'utf8'));
//responce()
});
If you have your javascript object, try:
res.status(200).json({
your_javascript_object
});
Put this instead for your /userget route.
```
res.setHeader('Content-Type', 'application/json');
var fs = require('fs');
res.send(JSON.parse(fs.readFileSync('database.json', 'utf8')));
```
This is a Node project, I'm getting a 'Cannot GET/' error when I try top open up localhost on port 8081. I'm almost certain it's just not reading in the HTML file correctly but I'm not sure.
var express = require('express');
var jsonfile = require('jsonfile');
var bodyParser = require('body-parser');
var app = express();
var file = 'C:/xampp/htdocs/codedb.json';
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('codeStore'));
app.use(bodyParser.json());
app.get('/backEndVersion.html', function (req, res) {
res.sendFile( __dirname + "/" + "backEndVersion.html" );
})
app.get('/somepath',function(req,res){
res.render('backEndVersion.html')
})
When u request somepath u will be rendered the backEndVersion.html file
I suggest u better use ejs or hbs engine for html renderering in nodejs
ejs link
I think you forgot to let the server listen to request. At the end of your file, add :
app.listen(8081)
I have two files - user.js and dataserver.js.
The dataserver.js contains this express.js and node.js API:
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())
var quotes = [];
app.get('/quote', function(req, res) {
var q = quotes[req.params.id];
res.json(q);
});
app.post('/quote', function(req, res) {
var newQuote = {
author : req.body.author,
text : req.body.text
};
quotes.push(newQuote);
res.json(true);
});
What I want is to have a command line run time input in command prompt like this after running user.js in node.js
/********
Enter Operation
[1] Show All Quotes
[2] Add Quotes
[3] Exit
*/
It sounds like you just need to output a message and then use the below module to prompt the user for input on one of the options.
Try the below module for handling shell prompts.
$ npm install prompt
https://github.com/flatiron/prompt
I am reading Professional Node.js and i'm trying to understand connect HTTP middleware framework. I created a simple middleware that returns a function that replies with a custom test string:
function replyText(text) {
return function(req, res) {
res.end(text);
};
}
module.exports = replyText;
But when i try to use this middleware in a connect server. Node gives me an error:
/Users/socomo22/work/hello_world_app_v2.js:8
var app = connect.createServer(replyText('Hello World!'));
^
TypeError: undefined is not a function
But when i simply use:
var app = connect();
app.listen(8080)
It runs without giving any error. I don't understand whether i'm doing any syntatical mistake. How would i use this simple middleware? This is my connect server file:
var connect = require('connect');
// middlewares
var replyText = require('./reply_text');
var app = connect();
var app = connect.createServer(replyText('Hello World!'));
app.listen(8080, function() {
console.log('listening on 8080 port')
});
As pointed by documentation use use API to mount a middleware and a http module to create an instance of server although you can create an instance just with connect as pointed here.
As pointed by #FranciscoPresencia adding .js extension while you require a your local module is optional.
var replyText = require('./reply_text.js');
So your code should look like this and i tested it. Working as intended
var connect = require('connect')
var http = require('http')
var app = connect();
// middlewares
var replyText = require('./reply_text.js');
app.use(replyText('Hello World!'));
http.createServer(app).listen(8080, function() {
console.log('listening on 8080 port')
});
Note: Try to avoid ports like 8080, 80 etc as its a reserved ports that might be used by other apps. This sometimes may cause node to fail.
Adding the output screenshot for your reference
Here You can start server in this way...
var connect = require('connect');
var http = require('http');
var app = connect();
var replyIN = require('./connetFile.js')
app.use(replyIN('Hello there m back again'));
http.createServer(app).listen(8888,function(){console.log('Server has started');});
And this is your connectFile.js
function replyIN(text){
return function (req, res) {
res.end(text);
};
};
module.exports = replyIN;