how to use post method in nodejs? - node.js

I am using post method in nodejs
Well it is working fine when I run it using postman
but when I run it in my browsers it shows error
Cannot GET /listUsers
and
listUsers:1 GET http://localhost:8081/listUsers 404 (Not Found)
this
here is my node js code
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.post('/listUsers', function (req, res) {
var f = parseInt(req.body.f);
console.log("hello" + f);
var l = parseInt(req.body.l);
var sum = Number(f + l);
res.send('The sum is: ' + Number(sum));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
here is my jquery code from where I am sending data
usid();
function usid(med){
var f = "my new name";
$.ajax({
crossDomain: true,
url:"http://localhost:8081/listUsers",
method:"POST",
data:{med,f:f},
success:function(data,status){
console.log("send");
}
})
}
can I get where I am doing mistake?

You are not submitting any form/storing any resource. What you are trying should ideally be done with GET.
Reasons it is not working with browser:
Visiting a page by changing url is a GET method. You do not have a GET method defined in your app for this route. Only one POST method.
What you can do:
Change POST to GET both in server and your AJAX. Change both methods accordingly. You will then have to pass query params(google something and everything after the question mark is how query Params work).

Related

Error when requesting API from Angular and Nodejs

I am attempting to use a Nodejs server as a proxy server to get around CORS of specific API's, such as darksky.net or googleapis. As shown in my Angular 8 code below, I try to send a get request to my NodeJS server, passing three parameters. Once the NodeJs server has received these parameters, I request the API, but I get a 404 error in return.
Angular code:
this.http.get('search/coords/',
{
params: {
address: this.street,
city: this.city,
state: this.state
}
}).subscribe(data => {
this.lattitude = data['results']['geometry']['location']['lat'];
this.longitude = data['results']['geometry']['location']['lon'];
console.log(this.lattitude);
console.log(this.longitude);
this.coords = {
lat: this.lattitude,
lon: this.longitude
};
});
return this.coords;
}
And here is my current Nodejs/Express code:
const express = require('express')
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
var request = require('request');
const app = express();
var url = "";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended': 'false'}));
app.use(cors());
app.get('search/coords/', function (req, res) {
var street = req.query.address;
var city = req.query.city;
var state = req.query.state;
url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + street + "," + city + "," + state + "&key=blah/"
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
res.send(info);
}
})
});
Specifically, I receieve a GET 404 not found error and an ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/search/coords/?address......." I'm new to angular and nodejs, so any help would be much appreciated.
There are two problems:
First is that you did not start the Node server
Second is that if you call this.http.get('search/coords', ...) then the default domain for that request is the current one, which is http://localhost:4200 and that is not you Node server port.
To make it work, you need to address both of the above.
So firstly, add this code to the Node.js server file (at the very bottom) to make it listen on some port:
app.listen(3000, () => {
console.log('Listening on port', 3000);
});
Then, modify your Angular code to make it look like this:
this.http.get('http://localhost:3000/search/coords/', ....);
It should work that way.

Axios can GET but not POST to the same URL

I'm building a react app
In one component I'm writing this GET request which works:
In another component I'm writing this POST request:
Which then returns this 404 error:
And I have no idea how my GET works but my POST returns 404:not found when I'm requesting the same file both times?
UPDATE:
I'm running a node.js server now but it's a bit of a frankenstein's monster as this really isn't an area I have an understanding of. Does anyone know what I'm doing wrong?
// Server setup from node.js website
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// Trying to listen for data from React app to feed into JSON (broken)
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/scene-setup.json", function(request, response) {
console.log(request.body); //This prints the JSON document received (if it is a JSON document)
});
app.listen(3001);
// Updating JSON file with "obj" (working)
var jsonfile = require('jsonfile')
var file = './scene-setup.json'
var obj = {name: 'JP'}
jsonfile.writeFile(file, obj, function (err) {
console.error(err)
})
Axios is used for making HTTP requests. So, you should have a backend server running that can handle these requests. I am not sure what exactly is the data that you want to save. If you need access to that data, should be saving it on the backend.
If you want to save some data just on the client side, HTML5 filesystem API might be something you want to look at. It can manage some data in the limited sandboxed part of user's filesystem.

is this the correct way to send data received from twitter api to the browser using nodejs?

I am still learning nodejs and was listening to daniel shiffman's video on how to setup the twitter api and how to get data from it.
Now, the code was working and I was getting back data, but it was all happening in the terminal.
What I wanted to do was to show the twitter data in my browser and wasnt sure how to do that. I tried searching for it, but didnt get much help.
So, I just tried doing whatever I knew and it worked and therefore I am still not sure that the code I have written is the proper way to do this.
I'd love to know if there's a mistake somewhere or If there's some other way I should have done this.
Anyways, here's the code
var http = require('http');
var express = require('express');
var app = express();
var port = 8080; // Use 8080 for local development because you might already have apache running on 80
console.log('The bot is starting');
var Twit = require('twit');
var config = require('./config');
console.log(config);
var T = new Twit(config);
var params ={
q:'spider',
count:5
}
T.get('search/tweets', params, gotData);
function gotData(err, data, response) {
var tweets = data.statuses;
app.get('/',function(req,res){
req=params;
var tweetz='';
for(var i=0;i<tweets.length;i++){
console.log(tweets[i].text+'================================');
tweetz = '<p>'+ tweetz+tweets[i].text+'</p>';
}
res.send(tweetz);
});
}
app.listen(port, function () {
console.log(`app listening on port ${port}!`);
});
The mistake you are doing is declaring app.get inside the callback.
app.get("/", function....) is a route which responds to GET requests which means whenever a user requests for "/", the callback which is the function(req, res) is called.
So the code should be:
app.get("/", function(req, res) {
// User requested for "/" route, now get tweets
T.get('search/tweets', params, function(err, data) {
//Tweets received, now send the tweets to the user
var tweets = data.statuses;
return res.send(tweets);
})
})
Then go to http://localhost:8080/ and it should work.

Creating web server with express (node.js)

js and am trying to create a web server and server side code for my web application.
I understand express is used to get access to all static files.
I am trying to start a simple server using express as follows:
var express = require("express");
var url = require("url");
var http = require("http");
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/Client"));
http.createServer(app).listen(port, function(req,res){
console.log("Server running at: " + "http://" + port);
res.writeHead(200,{
"Content-Type":"text/plain"
});
});
I cant seem to do anything with my res variable in my callback, which I am trying to use as a response object. Allowing me to do things like:
res.end(¨hello world¨);
Is this callback even allowed, or how can I start sending responses etc. I am on virtual box (linux) machine, and using res always gives error (undefined methods etc.). Thanks in advance,
http.createServer(app).listen(port, [hostname], [backlog], [callback])
There are no parameters given to the callback function. This is why req and res are undefined.
So you may change your code to:
app.listen(port, function(){
console.log("Server running at: " + "http://localhost:" + port);
});
app.get('/', function(req,res) {
res.status(200).send('Hello World!')
})
So take a look at the documentation of app.listen() and app.get()

nodejs express close server when request is done

I'm writing a test script for my module and I need to be able to close my server when my request is done. The following code works but I can see that app.close() was dropped from express 3. What's the best way to do it now?
var testCase = require('nodeunit').testCase;
var request = require('request');
var express = require('express');
var app = express.createServer();
var srv = app.listen();
....
request({
method: 'POST',
json: true,
body: { id: 'second request'},
url: 'http://' + target
}, function(err, res, body) {
console.info("closing server");
app.close();
test.done();
});
});
Thanks,
Li
p.s. test.done() must be called after closing the server, otherwise the test will fail.
Express applications used to inherit from http.Server, which they no longer do, and that's where the close method came from. Instead, call close() on your srv instance. You may commonly see this code written as:
var app = express.createServer();
var srv = require('http').createServer(app);
srv.listen(port);
According to the documentation for app.listen():
Bind and listen for connections on the given host and port, this method is identical to node's http.Server#listen().

Resources