I'm trying to go through the expressJS tutorial. This is my server code:
var express = require('express');
var app = require('express').createServer();
app.use(express.bodyParser());
app.post('/', function(request, response) {
console.log('Inside the post request!');
console.log(request);
response.send(resquest.body);
});
app.listen(3000);
and here is the POST request I am simulating:
$.ajax({
url: 'http://localhost:3000',
type: 'POST',
datatype: 'json',
data: {hello: 1},
success: function () {
console.log('Success!');
},
error: function () {
console.log('Error!');
}
});
The problem is that the request object does not seem to contain data: {hello: 1}. Instead it is a big mess of under-the-hood parameters. Am I doing something stupid?
I think that since you're not setting the content type to multipart/form-data it's assuming form encoded data. In which case, you'd set your data in your ajax request to be:
data: 'hello=1'
Set your content-type to: application/x-www-form-urlencoded
Access it via request.body.hello. It's been awhile, but try that.
You've written resquest.body instead of request.body; when you fix that, you'll be able to use request.body.data as others have pointed out.
You need to look at request.body. When you do request.body, you get {hello: 1}.
Related
I'm trying to make a GET request to a URL and getting an image from there as a response using node and express.
This is my code:
var app = require('express')();
var http = require('http').Server(app);
app.get('http://tapas.clarin.com', (req, res) => {
res.sendFile('index.html');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
The view is showing a Cannot GET /.
How can I make this request work properly to show the recieved image in my view ?
HTML
<div id="tapas">
// I want to show the image from the response here!
</div>
<script src="./app.js"></script>
</body>
app.get() is used to create a GET API on your server. What you need is a package that can help you to make API calls to other servers and fetch data from there.
You could use the request-promise npm package to make life easier for you.
var rp = require('request-promise');
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx' // -> uri + '?access_token=xxxxx%20xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
console.log('User has %d repos', repos.length);
})
.catch(function (err) {
// API call failed...
});
EDIT: After re-reading your question, you don't really need to do a GET API call and fetch the image on your server before showing it on your website. You could directly pass the URL to your img tag like this -
<img src="https://url/image.png" alt="example">
I am trying to do a simple post from Reactjs to a node.js server using node-fetch; however, the body of my request is always empty (I have not been able to come up with any configuration which results in a non-empty body). I have read seemingly every stackOverflow question about this and none solves my predicament, sadly. Here is my reactjs code:
fetch('http://localhost:3000/sayhello/', {headers: new Headers({
'Content-Type': 'application/json'
}), method: 'POST', body: {"nose":"bop"} })
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
And my server.js:
...
import BodyParser from 'body-parser';
app.use(BodyParser.urlencoded({extended : true}));
app.use(BodyParser.json());
app.post('/sayhello/', function(req, res) {
console.log(req.body);
res.send(req.body);
});
The console always gives an empty body, and the response is always undefined. This happens too when rather than JSON I just post a string as body. Any ideas?
Thanks
Not to worry friends it seems I have figured it out. I was missing JSON.stringify in body. I hope this helps someone sometime, so they avoid pulling out as much hair as I did :)
I am not able to get the data in the http post method of express nodejs.I am posting data from angular2. When i inspect in the network section of chrome, the payload is visible but the same data is received blank at app.post method.Please help me.
angular2 code
this.headers = new Headers();
this.headers.append('Content-Type', 'x-www-form-urlencoded');
let body = JSON.stringify({name:"Lionel Messi"});
return this.http
.post('http://localhost:8081/save',body
,this.headers);
}
nodejs code
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/save', function (req, res) {
console.log("Got a POST request for the homepage");
console.log(req.body);// output - {}
res.send('Hello POST');
})
Network Section in Chrome....payload is proper
alert method in node.js will not work . You need to use console.log("Hello");
Second thing is to get body data , use req.body.name
My way of writing code is like below and it works
$http({
method: 'POST',
url: 'http://localhost:8081/save',
data: {name:"Lionel Messi"}
})
.success(function(data) {
return data
})
.error(function(error) {
// handle error
});
Other way you can try is:
$http.post('http://localhost:8081/save', {name:"Lionel Messi"})
.then(function(data) {return data})
.catch(function() {console.log("Error Occured");});
You can do it like this-
Suppose you have sent username and password from your browser by post method.
app.post("/ url,function(request,response)
{ var username=request.body.username;
var password=request.body.password;})
I'm using a combination of Express and Request (installed using npm) to try to send a get request to get some json from the server. However no matter what I do the body that is returned is "undefined".
This is the code in my server.js file. The json isn't actually what I'm sending, it's just an example as I can't post what I'm actually sending.
import express = require("express");
import bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
})
app.listen(3000);
I've tried both of the following but both of them say that body is undefined.
import request = require("request");
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
this.config = JSON.parse(body);
})
request(`/config`, function(err, res, body) {
this.config = JSON.parse(body);
});
Does anyone know what I'm doing wrong? I've never used express or request before so any tips would be greatly appreciated.
UPDATE
If I change the request code to the following, the inside of the function is never run. Does anyone know why this would be?
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
console.log("response => "+JSON.parse(body));
return JSON.parse(body);
})
Since OP hasn't got it working and I believe the code he got up there is correct. I may as well post my working solution here to help him get started.
Hopefully this will save you hours of debugging...
Client:
"use strict";
let request = require("request");
let req = {
url: `localhost:4444/config`,
proxy: 'http://localhost:4444',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
request(req, function (err, res, body) {
this.config = JSON.parse(body);
console.log("response => " + this.config);
});
Server:
"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var config = require('config');
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
});
// Start the server
app.set('port', 4444);
app.listen(app.get('port'), "0.0.0.0", function() {
console.log('started');
});
Output:
response => {name: test}
I dont't know if you have posted whole of your server's code, it seems like you missed app.listen(port) so that your server cannot be started up correctly.
Also, if you added if (error) { console.log(error); } at the first line of the callback function of request, you'll find it print an error: [Error: Invalid URI "/config"]
And that's why the body is always undefined: You have to give the full url such like http://localhost:xxxx to request.
In short:
Your server didn't listen to a specific port. app.listen(5678)
Your client didn't know the complete url. request('http://localhost:5678/config', (...)=>{...})
I have an Node.js, Express app that serves as an REST api for Emberjs RESTAdapter. I trying to get this working on Windows Azure. When Ember makes the HTTP request on "/examples/1" as below gives me a 400, Bad Request.
After troubleshooting it seems like the error depends on the request header content type.
Visiting the "(domain)/users/1" in a web-browser prints out the correct json in the browser window.
Running Jquery ajax calls gives me the following results:
This does not work:
$.ajax({
url: "/users/1",
contentType: "application/json; charset=UTF-8"
}).done(function(data) {
console.log(data);
});
But, when switching to this, it works.
$.ajax({
url: "/users/1",
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
}).done(function(data) {
console.log(data);
});
Now, how do I set up my nodejs/azure solution to allow http requests with content type: "application/json; charset=UTF-8"?
Update
After comments, this is the server side code
var express = require('express');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
app.use('/', express.static(__dirname + '/WebContent'));
app.use(express.cookieParser());
});
app.get('/:param/:id', function(req, res) {
res.json(200, {user: {id:1, name: 'tester'}} )
});
app.get('/:param', function(req, res) {
res.json(200, {users: [{id:1, name: 'tester'}]})
});
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
I know this is an old question, but I think I may have also run across this and found a solution. For me, the problem is the way express treats the empty body as invalid JSON when you set the ContentType: application/json header on a GET request.
The suggested work around is to set the contentType to text/plain if you are not sending data.