I'm trying to request the json file from stackexchange api and when the server loads save it on the client side so I can manipulate/change it locally.
I tried using this code but page just keep loading and nothing happens.
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res, next) => {
request(surl, (error, response, body) => {
// res.setHeader("Content-Type", "application/json; charset=utf-8");
res.json(body)
console.log('body:', body);
console.log('body:', req.body);
});
});
app.listen(3000, () => { console.log('On port 3000...') });
And if I comment out these two lines in my code below
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
It gives this kind of output.
"\u001f�\b��\u0000��8z00\u0000^{4���=�c��\u0000��#c�\u0002\u0000\u0000"
If anyone could give me a start that would be great! Thanks.
The output is gibberish because body is gzip compressed. It's not JSON, not even text:
To return it to browser, the easiest way is using pipe:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request(surl).pipe(res);
});
Or, if you want to manipulate/change the body, gzip: true option can be used:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request({
url: surl,
gzip: true
}, function(error, response, body) {
let bodyObj = JSON.parse(body);
// change bodyObj...
res.json(bodyObj);
});
});
Related
I'm on my localhost and when i start the server it shows nothing. When i go to localhost:8080/register it should show "asdasd" (as you can see in the code) but it doesnt work.
Can you guys help me out? Thank you very much!
const U2F = require("u2f");
const Express = require("express");
const BodyParser = require("body-parser");
const Cors = require("cors");
const HTTP = require("http");
const FS = require("fs");
const session = require("express-session");
const APP_ID = "http://localhost:8080/";
var app = Express();
app.use(session({ secret: "test", cookie: { secure: true, maxAge: 60000 }, saveUninitialized: true, resave: true }));
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
app.use(Cors({ origin: [APP_ID], credentials: true }));
var user;
app.get("/", (request, response, next) => {
response.end("Hello Test");
});
app.get("/register", (request, response, next) => {
console.log("asdasd");
});
app.post("/register", (request, response, next) => {});
app.get("/login", (request, response, next) => { });
app.post("/login", (request, response, next) => { });
HTTP.createServer(function (request, response){
response.end();
}).listen(8080);
1) for a start your are logging "asdasd" to the console and not responding to the request made at the "/register" endpoint, just modify your code to the one below.
app.get("/register", (request, response, next) => {
response.end("asdasd");
});
2) you have not actually created a server for app , http.createserver is not tied to app
modify your code to the below
const server = HTTP.createServer(app);
server.listen(8080,()=>console.log("server is listening on port 8080")
Just pass app(returned by express) inside HTTP.createServer
HTTP.createServer(app).listen(8080);
My project is bundled on webpack. I've a form which post data to other local server, where saving in txt file. All is okay, data saves correctly, but after a few minutes, on client returns alert "net::ERR_EMPTY_RESPONSE" and then the same form values save to file second time. Why is it saves twice? How to fix this problem.
My fetch post request:
fetch("http://localhost:4000/post", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify(fragment),
if(err) {
throw err;
}
})
.then(console.log(fragment))
.catch(alert);
My server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs');
const cors = require('cors');
app.get('/', (req, res) => {
res.send('hello')
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors({
allowedOrigins: [
'http://localhost:9000'
]
}));
app.get('/post', (req, res) => {
console.log(req.body)
res.send('post')
})
app.post('/post', (req, res) => {
res = 0;
if (req.body.film.includes('день: Понеділок')) {
fs.appendFile('booking.monday.txt',
`${req.body.name},${req.body.number},${req.body.film}\n`,
function (err) {
if (err) throw err;
console.log('Saved!');
});
}
})
I'm new to Node and I can't seem to get my request to complete. I'm just trying to create a basic handshake between server and client by sending the location for the client to the server and displaying that into the server log. I'm not sure why I can't display the data into the log.
Index.js
const express = require('express');
const app = express();
app.listen(8080, () => console.log('listening at 8080'));
app.use(express.static('public'));
app.use(express.json({limit: '1mb'}));
app.post('/api',(request,response) => {
console.log('I got a request!');
console.log(request.body);
});
Index.html
<script>
if('geolocation' in navigator) {
console.log('geolocation is avaliable');
navigator.geolocation.getCurrentPosition(async position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
console.log(lat,lon);
document.getElementById('latitude').textContent = lat;
document.getElementById('longitude').textContent = lon;
const data = {lat, lon};
const options = {
method: 'POST',
header:{
'Content-Type':'application/json'
},
body: JSON.stringify(data)
};
fetch('/api',options);
});
} else{
console.log('geolocation is not avaliable');
}
</script>
Some things to note. The request does seem to complete and no errors are shown in the developer console.
Server information:
-[nodemon] restarting due to changes...
-[nodemon] starting node index.js
-listening at 8080
-I got a request!
-{}
Add the following to your index.js:
npm i -S body-parser
// Takes the raw requests and turns them into usable properties on req.body
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/api', (request, response) => {
console.log('I got a request!');
console.log(JSON.stringify(request.body));
});
Try the following code in your index.js
const express = require('express')
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
}
next();
});
everyone, I am a beginner in nodejs and expressjs. So while practicing I got a question in my mind is that I am having one URL from where I want to fetch data and I simply did it.
Following is the code:
var express = require('express');
var app = express();
var request = require('request');
var bodyParser = require('body-parser');
app.set('view engine', 'ejs');
var urlencoderparser = bodyParser.urlencoded({ extended : true });
var data;
app.get('/', function (req, res) {
request.get('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json', function(err, res, body){
if(err) {
return console.log(error);
}
data = JSON.parse(body);
});
res.render('index', {data: data});
console.log(data);
});
app.listen(3000);
And this code is working fine.
Then I thought to change the URL by passing values using form.
we can enter a value in the form. The value should be either XML or JSON and according to that it will change the URL like the code given below:
var url = 'http://mysafeinfo.com/api/data?list=englishmonarchs&format='+form_data
Now for this, I tried request.post() in this way:
app.get('/', function (req, res) {
Request.post({
"headers": { "content-type": "application/json" },
"url": "http://mysafeinfo.com/api/data?list=englishmonarchs&format="+form_data,
}, (error, response, body) => {
if(error) {
return console.log(error);
}
data = JSON.parse(body);
});
res.render('index', {data: data});
});
app.listen(3000);
But this is not working.
Please help me to know where I am wrong and whether this way is correct for coding in nodejs or expressjs?
Hello everyone i am adding whole code with you for more clearance
var express = require('express');
var app = express();
var request = require('request');
var bodyParser = require('body-parser');
app.set('view engine', 'ejs');
var urlencoderparser = bodyParser.urlencoded({ extended : true });
app.get('/', function(req, res){
res.render('index');
});
app.post('/', urlencoderparser, function(req, res){
res.render('form-data', {data : req.body});
request.post({
"headers": { "content-type": "application/json" },
"url": "http://mysafeinfo.com/api/data?list=englishmonarchs&format="+req.body.name,
}, (error, response, body) => {
if(error) {
return console.log(error);
}
data = JSON.parse(body);
});
console.log(req.body);
});
app.listen(3000);
I am using cookie-parser in my express app. When the root page is requested I set a random number on the cookie using res.cookie(name, value) and it sets it fine (I checked on my browser console). But when I try to log req.cookie it always returns undefined.
Here's my code:
routes.js
var express = require('express')
var router = express.Router()
var movieTrailer = require('movie-trailer');
var Promise = require('bluebird');
var logs = require('log-switch');
var fs = require('fs');
//var cookieParser = require('cookie-parser');
//Setup x-ray for scraping
var Xray = require('x-ray');
var x = Xray();
var debug = false;
router.get('/', (req, res) => {
console.log('Page requested!');
console.log('Cookies: ', req.headers.cookies); // For some reason this returns undefined
var scrapeMovies = function(){
return new Promise((resolve, reject) =>{
fs.readFile('moviesRT.json', (err,data) =>{
var movies = JSON.parse(data);
resolve(movies);
});
});
};
scrapeMovies().then(
movies => {
var randomInt = Math.floor(Math.random() * movies.length);
res.cookie('randomInt', randomInt);
var randomMovie = movies[randomInt];
movieTrailer(randomMovie.title, (err, url) =>{
console.log('Requesting trailer: ', randomMovie.title);
if(err) throw err;
var embedUrl = url.replace('watch?v=','embed/');
console.log('Video ID: ', url.slice(32,url.length));
randomMovie.trailerURL = embedUrl; //Add the embed URL to the randomMovie object before rendering it
res.render('main',randomMovie,
(err, html) =>
{
if(err) throw err;
console.log('Rendering...');
res.send(html);
console.log("Done!");
});
});
});
});
module.exports = router;
app.js
const express = require('express');
//Define app and settings
const app = express();
const exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
const port = 3000;
var routes = require('./routes');
var debug = true;
app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
//app.use(cookieParser());
//View engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.listen(port, function () {
console.log(`Server Starts on ${port}`);
if(!debug) logs.disable(); //Disable logging if debug variable is false
});
You either want to check req.headers.cookie which will be set by express.
Or if you want to use the the parsed result of the cookie-parse middleware that is stored inreq.cookies then your problem is the order in which you register your routes and the middleware.
app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
The parsing of the cookie is done after the routes in routes have ben executed.
You need to move the cookieParser() before the route where you want to use it.
app.use(cookieParser());
app.use('/', routes);
app.use(express.static('public'));
This solved my problem:
Basically when you are sending a request to the server from client-side, make sure you add withCredentials: true. For example
{
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
}),
'withCredentials':true
};
This happened to me, when I sent a PUT request from the client-side (Angular) without passing the body object.
I was doing this (second argument missing):
requestBranchEditPermission() {
return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, this.options).toPromise();
}
instead of this:
requestBranchEditPermission() {
return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, {}, this.options).toPromise();
}
You will need to read the cookies as req.cookies['cookie-name'] and set the cookies as resInit.cookie('cookie-name', 'cookie-value')
This worked for me
in the frontend add credentials : 'include' as an option to your fetch API
A more elaborated code below for a get request
fetch('url', {credentials: 'include'})
.then(res => res.json())
.then(data => //do something with the data)
.catch(err => console.log(err.message));