get method not displaying the data on browser and put showing error on postman - javascript

I'm creating an API with JS. While using the get method I'm not receiving the JSON data from the ./personal_data.js file. It's only displaying closed braces as response.
I'm attaching the code and output below. Any suggestions might be helpful.
const express = require('express');
const personal_data = require('./personal_data');
const app = express();
app.listen(3000, () => {
console.log('Listening on port 3000');
});
app.get('/', (req, res) => {
res.json({ Message: 'API is Working' }); // show messsage on serv
});
app.get('/personal_data', (req, res) => {
res.json(personal_data); // send employee json file
});
app.post('/personal_data',(req,res)=>{
res.send('post request')
})
json file with data
OUTPUT
Post man

Make sure you're exporting your data correctly. Use module.exports = ... instead of module.export = ... in your personal_data.js. Don't forget to restart your server once it's updated.
Check this sandbox where I show you the difference: CodeSandbox

Related

whtsapp bot from twilio and nodejs - Wait for Reply

Trying to create a WhatsApp bot through twilio
Can send one sided messages
Unable to send a response message on a completed question
Sending sample code that doesn't work
From what it seems the reference to POST is not the correct reference
Thank you
app.post('/message', (req, res) => {
const message = req.body.Body;
if (message === 'hello') {
client.messages
.create({
body: 'Hello, how can I help you?',
from: 'YOUR_TWILIO_NUMBER',
to: 'USER_PHONE_NUMBER'
})
.then((message) => console.log(message.sid));
}
});
You don't need to use client.messages.create() if you "just" want to reply to an incoming message. This is possible but isn't recommended as the webhook call might return a error status code even though the reply was successful.
Instead, you can reply with a TwiML response:
const express = require('express');
const { MessagingResponse } = require('twilio').twiml;
const app = express();
app.post('/sms', (req, res) => {
const twiml = new MessagingResponse();
twiml.message('The Robots are coming! Head for the hills!');
res.type('text/xml').send(twiml.toString());
});
app.listen(3000, () => {
console.log('Express server listening on port 3000');
});
PS: Here's the related doc file for this use-case.

Express post request timing out in chrome

I am new to API development and am trying to create a post request and send data to an API but it keeps timing out in chrome. The error I am getting is net::ERR_EMPTY_RESPONSE.
This is my js where I am trying to send the info. It is called in another method called addToCart() where I am passing in the cart as a parameter.
function sendToAPI(cart) {
var req = new XMLHttpRequest();
req.open('POST', '/add');
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify({cart : cart}));
req.addEventListener('load', () => {
console.log(req.resonseText);
})
req.addEventListener('error', () => {
console.log('There was an error');
console.log(error);
});
}
This is where I am creating the API:
const express = require("express");
const bodyParser = require("body-parser");
const api = express();
api.use(express.static(__dirname + '/public'));
api.use(bodyParser);
api.listen(3000, function() {
console.log("Server is running on port 3000");
});
api.post('/add', function(req, res) {
console.log(req.body);
res.send("It works");
});
I see a couple problems. First, this is not correct:
api.use(bodyParser);
For a JSON response, you would do this:
api.use(bodyParser.json());
And, body-parser is built into Express so you don't need to manually load the body-parser module. You can just do this:
api.use(express.text());
Then, in your client-side code, this:
console.log(req.resonseText);
is misspelled and should be this:
console.log(req.responseText);
And, in your client-side code, you should also be checking the status code returned by the response.
FYI, the new fetch() interface in the browser is soooo much nicer to use than XMLHttpRequest.

req.body returns undefined while using body-parser

I'm trying to build an API that receives a POST req to create a user but I am getting undefined errors for all of my req.body requests. My app is set up like this (simplified for brevity):
User controller that gets called by Express Router in my user routes file
/controllers/user.js
userController.addUser = function(req, res) {
let user = new User();
user.username = req.body.username;
user.first_name = req.body.first_name;
user.last_name = req.body.last_name;
user.email = req.body.email;
user.type = req.body.user_type
// This returns undefined as does all other req.body keys
console.log("REQ.BODY.EMAIL IS: " + req.body.email);
}
User Route File:
/routes/user.js - requires user controller above
router.post('/user/create', userController.addUser);
Main App:
all routes and controllers work per my tests except where req.body.* is used
index.js - main app file
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', routes);
I have looked through the Express documentation and through countless StackOverflow posts with no luck. Let me know if you need further clarification.
My issue was how I was sending the body to the API endpoint. I was using form-data instead of x-www-form-urlencoded with Postman. User error
Sometime with change in version body-parser seems to not work, in that case just use following, this will remove dependency from body-parser:
router.post('/user/create', (req, res, next) => {
let body = [];
req.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
// Data is present in chunks without body-parser
body.push(chunk);
}).on('end', () => {
// Finally concat complete body and will get your input
body = Buffer.concat(body).toString();
console.log(body);
// Set body in req so next function can use
// body-parser is also doing something similar
req.body = body;
next();
});
}, userController.addUser);

Getting cannot POST / error in Express

I have a RESTful API that I am using postman to make a call to my route /websites. Whenever I make the call, postman says "Cannot POST /websites". I am trying to implement a job queue and I'm using Express, Kue(Redis) and MongoDB.
Here is my routes file:
'use strict';
module.exports = function(app) {
// Create a new website
const websites = require('./controllers/website.controller.js');
app.post('/websites', function(req, res) {
const content = req.body;
websites.create(content, (err) => {
if (err) {
return res.json({
error: err,
success: false,
message: 'Could not create content',
});
} else {
return res.json({
error: null,
success: true,
message: 'Created a website!', content
});
}
})
});
}
Here is the server file:
const express = require('express');
const bodyParser = require('body-parser');
const kue = require('kue');
const websites = require('./app/routes/website.routes.js')
kue.app.listen(3000);
var app = express();
const redis = require('redis');
const client = redis.createClient();
client.on('connect', () =>{
console.log('Redis connection established');
})
app.use('/websites', websites);
I've never used Express and I have no idea what is going on here. Any amount of help would be great!!
Thank you!
The problem is how you are using the app.use and the app.post. You have.
app.use('/websites', websites);
And inside websites you have:
app.post('/websites', function....
So to reach that code you need to make a post to localhost:3000/websites/websites. What you need to do is simply remove the /websites from your routes.
//to reach here post to localhost:3000/websites
app.post('/' , function(req, res) {
});

Cannot GET / DELETE Express.js

I have this script with which I'm trying to POST, GET and DELETE some stuff.
When I try POST or GET, the right messages are logged, but when I try DELETE, I get the following error:
Cannot GET /del_user
The URL I'm using is http://127.0.0.1:8081/del_user
What can be wrong in here?
var express = require('express');
var app = express();
// This responds with "Hello World" on the homepage
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Hello GET');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('Hello POST');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
console.log("Got a DELETE request for /del_user");
res.send('Hello DELETE');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
console.log("Got a GET request for /list_user");
res.send('Page Listing');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Page Pattern Match');
})
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)
})
I solved it by changing the app.delete to app.get and then placing the required remove statement inside the app.get. Something like this :-
app.get('/delete/:userId', (req, res) => {
Users.remove({ _id: req.params.userId }, (error, posts) => {
if (error) {
console.warn(error);
}
else {
data = posts
res.render("delete", {"data": data})
}
});
});
In your code you're binding the /del_user URL to the HTTP DELETE method.
So all you need to do is specify the DELETE method in your application or in Postman.
If you're not using it, it's an App in Google Chrome and you might want to download it, it makes your life a LOT easier ;)
Also, since the HTTP method is already declared to be DELETE, there is no need to specify it in the URL.
This is part of the RESTful working.
If you are using AJAX to try your code, you need to specify the method, which is delete.
$.ajax({
url: "http://127.0.0.1:8081/del_user",
type: "DELETE"
});

Categories