So i am using ionic framwork to make my app and using nodeJS as my backend but i am still a noob in this and i can't seem to figure it out still after 4 days so hopefully someone could answer this problem to me and why would be appreciated.
So for my ionic client side i do this to make a http.post request
progress() {
var headers = new HttpHeaders();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
let options = {headers: headers};
let postData = {
username: this.username,
email: this.email,
password1: this.password1,
password2: this.password2
};
this.http.post('localhost:4000/api/users', postData, options,).subscribe(
data => {
console.log(data);
},
error => {
console.log(error);
});
}
and this is what i am doing to get the data from the server but that's not working
// Packages
let express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var cors = require('cors');
const app = express();
app.use(cors({origin: 'http://localhost:8100'}));
const port = 4000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Whenever you enter localhost:4000/ //
app.get('/', function (req, res) {
res.send(('Server runs'));
});
app.listen(port, () => console.log(`app listening on port ${port}!`));
app.get('/api/users', (req, res) => {
res.send('api/users page');
request.get({
uri: 'http://localhost:8100/create-account'
}, function (err, res, body) {
console.log('error:', err); // Print the error if one occurred and handle it
console.log('statusCode:', res && res.statusCode); // Print the response status code if a response was received
res.send(body);
});
});
i also tried 'http://localhost:8100' & 'localhost:8100'
so someone help me
You need to add a handler for your POST request. To do this use app.post, and it looks like this
app.post('/api/users', (req, res) => {
// You can find your data here
const data = req.body;
console.log(data);
// Send back a response
res.sendStatus(200);
});
Related
I'm using NextJS for my application and i would like to write an JSON-file to the client in a function. On my localhost everything works fine and without any problem, but the application gets build and deployed to firebase it isn't working anymore.
I already tried multiple things, i already created the function in the api folder of NextJs and also created an localhost node server and call them in nextjs API as:
var fs = require('fs').promises;
export default function (req, res) {
console.log(JSON.stringify(req.body))
let Data= JSON.stringify(req.body)
fetch('http://localhost:9091/data', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: Data
})
.then((response) => {
console.log('here')
return response.json(); // or .text() or .blob() ...
})
.then((text) => {
console.log(text)
res.status(200)
// text is the response body
})
.catch((e) => {
// error in e.message
});
As said this works when the application runs on localhost but not on firebase hosting/functions.
The node server looks like:
var express = require('express');
var app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
var fs = require('fs').promises;
app.get('/', function (req, res) {
res.send('Hello World');
})
app.post('/data', function (req, res) {
res.send('Hello World');
let Order = req.body;
console.log(Order)
fs.readFile("object.json",'utf8').then(data =>{
let json = JSON.parse(data);
json.push(Order);
fs.writeFile("object.json", JSON.stringify(json)).then( () => { console.log('Append Success'); })
.catch(err => { console.log("Append Failed: " + err);});
})
})
var server = app.listen(9091, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
What I'm trying to achieve is that data is appended to the JSON file and stored locally on the client.
Does anyone have an idea how to handle this properly?
I am building an API that uses socket connection to interact with a server backend built in C#. This is what I have so far
const request = require('request');
const express = require('express');
const app = express();
var server = require('http').createServer(app);
var cors = require("cors");
app.use(cors());
const net = require('net');
const client = new net.Socket();
const stringToJson=require('./stringToJson')
const port = process.env.PORT;
const host = process.env.HOST;
client.keepAlive=true
client.on('close', function() {
console.log('Connection closed');
});
app.get('/getScores',function (req,res) {
let dataSend=''
client.on('data', function (data) {
console.log('Server Says : ' + data);
if(data!='ANALYSIS-ERROR'){
dataSend=stringToJson.stringToJson(data)
}
else{
dataSend=stringToJson.stringToJson('0:0.0:0.0:0.0:0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0')
}
client.destroy()
return res.send(dataSend)
});
client.connect(port, host, function () {
client.write(`GENERAL-ANALYSIS|${req.query.id}|${req.query.website}|`)
return
});
return
})
app.get('/getPlace',function (req,res) {
console.log(req.query)
request(
{ url: `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${req.query.name}+in+${req.query.city}&key=${process.env.API_KEY}` },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', message: error.message });
}
return res.json(JSON.parse(body));
}
)
})
//TODO ADD 404 500 PAGES
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
server.listen(9000, () => {
console.log(`App running at http://localhost:9000`);
});
Basically it creates a connection with the server and listens for some data to be sent back. Then processes the string and sends it to the React frontend. The api calls are made by the frontend using axios
It works but if you refresh the page it throws this error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How do I fix this?
Try setting the headers as found in the documentation request.setHeader(name, value)
request.setHeader('Content-Type', 'application/json');
I am trying to introduce gateway for my micro services. I got stuck in post method. Target server not receiving the request body. Not sure what i am doing wrong. Can any one help me out. Here is the code
const express = require('express');
const app = express();
const httpProxy = require('http-proxy');
const apiProxy = httpProxy.createProxyServer();
const server1 = 'http://localhost:4000',
server2 = 'http://localhost:4001';
apiProxy.on('proxyReq', (proxyReq, req) => {
console.log(' in proxy req ...');
if (req.body) {
const bodyData = JSON.stringify(req.body);
// incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
proxyReq.setHeader('Content-Type','application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
// stream the content
proxyReq.write(bodyData);
apiProxy.web(req,res, {target: server2});
}
});
app.all('/service1/*', (req,res) => {
console.log("redirecting to server1 ...");
apiProxy.web(req,res, {target: server1});
})
app.all('/service2/*', (req,res) => {
console.log(" req, body : ", req.body);
apiProxy.web(req,res, {target: server2});
})
apiProxy.on('error', (err,req,res) => {
console.log('got an error : ',err)
});
apiProxy.on('proxyRes', (proxyRes,req,res) => {
console.log(' got a response from the server ..');
return proxyRes;
})
app.listen(3000, () => console.log(' proxy running on 3000'));
By using the body parser i am able to print request body but not getting the request body on the target server.
const app = express();
const httpProxy = require('http-proxy');
const apiProxy = httpProxy.createProxyServer();
const server1 = 'http://localhost:4000',
server2 = 'http://localhost:4001';
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.all('/service1/*', (req,res) => {
console.log("redirecting to server1 ...");
apiProxy.web(req,res, {target: server1});
})
app.all('/service2/*', (req,res) => {
console.log(" req, body : ", req.body);
apiProxy.web(req,res, {target: server2});
})
apiProxy.on('error', (err,req,res) => {
console.log('got an error : ',err)
});
apiProxy.on('proxyRes', (proxyRes,req,res) => {
console.log(' got a response from the server ..');
return proxyRes;
})
app.listen(3000, () => console.log(' proxy running on 3000'));
I'm trying to POST an Item to my db in my json server. I'm sending the POST request from Angular. When I do so, I get the following error:
Note: when I do the get in a the GET end point it works fine. I'm very new on the server side
POST ERROR 404:
Http failure response for http://localhost:3000/addMember: 404 Not Found
SERVER.JS
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
....
app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);
app.use(
helmet({
noCache: true
})
);
app.use(
hsts({
maxAge: 15552000 // 180 days in seconds
})
);
app.use(
express.static(path.join(__dirname, 'dist/softrams-racing'), {
etag: false
})
);
app.get('/api/members', (req, res) => {
request('http://localhost:3000/members', (err, response, body) => {
if (response.statusCode <= 500) {
res.send(body);
}
});
});
// TODO: Dropdown!
app.get('/api/teams', (req, res) => {
request('http://localhost:3000/teams', (err, response, body) => {
if (response.statusCode <= 500) {
res.send(body);
}
});
});
// Submit Form!
app.post('/api/members', function(request, response) {
request.post('http://localhost:3000/members', (err, response, body) => {
if (response.statusCode <= 500) {
req.send(body);
}
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/softrams-racing/index.html'));
});
app.listen('8000', () => {
console.log('Vrrrum Vrrrum! Server starting!');
});
ANGULAR
addMember(memberForm: Member) {
this.http.post(`${this.api}/addMember`, memberForm).subscribe(
data => {
console.log('POST Request is successful ', data);
},
error => {
console.log('Error', error);
}
);
}
UPDATE:
in my console i see this POST /addMember 404 12.105 ms - 2 and If i go to http://localhost:3000/addMember directly in the browser I see an empty object {} and if I go here http://localhost:3000/ I see this message To access and modify resources, you can use any HTTP method GET POST PUT PATCH DELETE OPTIONS
The issue here is that you are making your POST request to a route which your JSON server does not handle. Change the URL to http://localhost:3000/members, and it should work fine!
(The routes on a json-server correspond to the elements in your db.json file.)
Try to change your code like this:
addMember(memberForm: Member) {
this.http.post(`${this.api}/api/addMember`, memberForm).subscribe(
data => {
console.log('POST Request is successful ', data);
},
error => {
console.log('Error', error);
}
);
}
From the error it is shown that your service is expecting the request at http://localhost:3000/api/addMember but your console.log shows that you are sending post request at http://locatlhost:3000/addMember
I'm trying to make a simple POST request but I'm getting an empty response back from the server. I've sifted through all the SO questions regarding this topic and tried the solutions posted but to no avail.
I've tried changing the request header options to use 'application/x-www-form-urlencoded' and set bodyParser in my express app as app.use(bodyParser.urlencoded({ extended: true })); but that didn't work either.
auth-service.service.ts
login(loginInfo: object) {
return this.http.post<loginInfo>(this.loginUrl, { "test": "test" })
.pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log('An error occured:', error.error.message);
} else {
console.log(`Backend returned code ${error.status}, ` +
`body was ${error.error}`);
}
return throwError('Something bad happened; please try again later.')
}
login.component.ts (calls the login service method)
onSubmit() {
const loginInfo = { username: this.username.value, password: this.password.value };
this.authService.login(loginInfo).subscribe(
resp => { console.log(resp); },
err => { console.log(err); }
)
}
server.js (I've defined routes here but they're not relevant)
const express = require('express');
const bodyParser = require('body-parser');
const api = require('./routes/api');
const app = express();
const port = process.env.port || 3000;
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
})
app.use(bodyParser.json());
app.use('/api', api)
app.get('/', function (req, res) {
res.send(JSON.stringify('Hello from server'));
})
app.post('/login', (req, res) => {
let userData = req.body
res.send('Request body: ' + JSON.stringify(userData));
})
app.listen(port, function () {
console.log('Server running on localhost: ' + port);
});
I'm console logging the following:
Backend returned code undefined, body was undefined
Something bad happened; please try again later.
When I try using Postman, however, I get the response I expect (i.e. Request body: {})
I'm not sure as to why a response is retrieved when done through Postman but not when done through the app.
Any help is appreciated. Thanks!
You need to set body for POST request in auth-service.service.ts:
import { HttpParams } from '#angular/common/http';
login(loginInfo: object) {
const body = new HttpParams()
.set('test', 'test');
return this.http.post<loginInfo>(this.loginUrl, body)
.pipe(
catchError(this.handleError)
);
}
try using express.json its missing
app.use(express.json());
and
app.use(bodyParser.urlencoded({
extended: true
}));