I try to write CRUD and checking it up with Postman.
When I use a debugger at the end of the post request it's working.
Problem: When I remove the debugger and try to run the code nothing happens - only error: "Could not get any response". How can I make my post to work well without debugger?
***For example, I send this as JSON through postman like this:
{
"id":3,
"name": "Ron",
"phone": "01323133333"
}
this is the relevant code:
index.js:
const express = require('express');
const app = express();
db = require('./db');
app.use(express.static('public'));
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const port = 1400;
app.listen(port,()=>{
console.log(`Server is running on port ${port}`);
})
//post request:
app.post('/user' , (req,res)=> {
const {body} = req,
{id,name,phone} = body
db.query(`INSERT INTO public.users(
id, name, phone)
VALUES (${id}, '${name}', '${phone}');`,(err,dbRes)=>{
if(err)
res.status(400).send(err);
else
{
res.send(dbRes.rows);
}
})
})
db.js:
const {Client} = require ('pg');
const client = new Client ({
user:'postgres',
host:'localhost',
database:'nodeapp',
password:'123456',
port:5432
})
client.connect();
module.exports = client;
Thank you !
Related
Express App showing cannot find after deploying on cPanel. I have tried to sort out this issue also when I write server.listen() it works great but when I write app.listen() it gives cannot find message.
I tried default Node Js code (last 10 lines except app.listen() ) which works fine while app.listen() not working:
const express = require("express");
const multiparty = require('multiparty');
const mongoose = require("mongoose");
const morgan = require('morgan');
const { createHttpTerminator } = require('http-terminator');
const fs = require('fs');
const cors = require('cors');
const crypto = require('crypto');
require('dotenv').config();
const { MongoClient, ServerApiVersion } = require('mongodb');
const {Product, Service, Home, HireMe } = require('./models/Product');
const app = express();
app.use(morgan('tiny'));
app.use(express.static('public'));
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Home Page...!');
});
app.get('/offers', async (req, res) => {
try {
const result = await Product.find({});
res.send("result");
} catch (err) {
res.send({ 'error': err.message });
}
})
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(app);
});
server.listen(); //It works
app.listen (); // Showing Cannot find message
I solved this error by prefixing the URL link (on which I created node JS on cPanel) to routes. Now it works great.
my code was perfectly working a couple of days ago and it suddenly stopped working it's connected to the mongodb cluster but i fail to receive response from the database everytime i send a request it's i tried reinstalling node reinstalling mongoose updating all packages but nothing seemed to work
keeps loading forever
and no response when i cancel it
here's the server.js code :
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const cors = require('cors')
require('dotenv/config');
const authJwt = require('./helpers/jwt')
const errorHandler = require('./helpers/error-handler')
const api = process.env.URL;
mongoose.connect(process.env.DATABASE,
{
useNewUrlParser:true,
useUnifiedTopology:true
})
.then(()=>{
console.log('connected to database')
})
.catch((err)=>{
console.log(err)
})
//variables
const app = express();
const port = 9090
//middleware calls
app.use(bodyParser.json());
app.use(morgan('tiny'));
app.use(express.Router())
//app.use('')
app.use(cors());
app.options('*',cors())
app.use(errorHandler)
app.use(authJwt)
const categoriesRouter = require('./routers/categories')
const productsRouter = require('./routers/products')
const ordersRouter = require('./routers/orders')
const usersRouter = require('./routers/users')
//Routers
app.use(`${api}/categories`,categoriesRouter)
app.use(`${api}/products`,productsRouter)
app.use(`${api}/users`,usersRouter)
app.listen(port,(req,res)=>
{
console.log('server is running in port '+ port )
})
here's one of the routers code :
const {Category} = require('../models/category')
const express = require('express');
const router = express.Router();
router.get('/',async(req,res)=>{
const categoryList = await Category.find();
if(!categoryList)
{
res.status(500).json({success:false})
}
res.status(200).send(categoryList);
})
router.get('/:id',async(req,res)=>{
const category = await Category.findById(req.params.id)
if(!category)
{
res.status(500).json({message:'The category with the given ID'})
}
res.status(200).send(category)
})
router.post('/',async(req,res)=>{
let category = new Category({
name:req.body.name,
icon:req.body.icon,
color:req.body.color
})
category = await category.save();
if(!category)
return res.status(404).send('the fag category cannot be created')
res.send(category)
})
router.delete('/:id', (req,res)=>{
Category.findByIdAndRemove(req.params.id).then(category=>{
if(category)
{
return res.status(200).json({success:true,message:'the category is deleted'})
}
else
{
return res.status(404).json({success:false,message:'the category is not found'})
}
}).catch(err=>{
return res.status(400).json({success:false , error: err})
})
})
router.put('/:id',async (req,res)=>{
const category = await Category.findByIdAndUpdate(
req.params.id,
{
name:req.body.name,
icon:req.body.icon,
color:req.body.color
},
//i want to return the new updated data
{ new:true }
)
if(!category)
{
return res.status(400).send('The category cannot be created!');
}
res.send(category);
})
module.exports = router;
just to let you know it was working a couple of days ago and now it just suddenly stopped working if there's anything i can do or if you've faced the same problem before please reach out
Make sure to send a proper response on the api side of code.
In the case that u are using the express framework, it could look something like this:
router.get('/', (req, res) => {
res.status(200).json({
your: data
})
})
Right now I have a front end react application using axios and and a backend server using node.js and express. I cannot for the life of me get my serp api data to post so that my front end can get it through axios and display the json data. I know how to get data to the front end but I am not a backend developer so this is proving to be incredibly difficult at the moment. I'm able to get the data from the the external api, I just don't know how to post it once I get it. Also I would not like to have all these request running on server.js so I created a controller but I think that is where it is messing up. Any help is appreciated
//pictures controller
const SerpApi = require('google-search-results-nodejs');
const {json} = require("express");
const search = new SerpApi.GoogleSearch("674d023b72e91fcdf3da14c730387dcbdb611f548e094bfeab2fff5bd86493fe");
const handlePictures = async (req, res) => {
const params = {
q: "Coffee",
location: "Austin, Texas, United States",
hl: "en",
gl: "us",
google_domain: "google.com"
};
const callback = function(data) {
console.log(data);
return res.send(data);
};
// Show result as JSON
search.json(params, callback);
//res.end();
}
// the above code works. how do i then post it to the server so that i can retrieve it to the backend?
module.exports = {handlePictures};
//server.js
const express = require('express');
const app = express();
const path = require('path');
const cors = require('cors');
const corsOptions = require('./config/corsOptions');
const { logger } = require('./middleware/logEvents');
const errorHandler = require('./middleware/errorHandler');
const cookieParser = require('cookie-parser');
const credentials = require('./middleware/credentials');
const PORT = process.env.PORT || 3500;
// custom middleware logger
app.use(logger);
// Handle options credentials check - before CORS!
// and fetch cookies credentials requirement
app.use(credentials);
// Cross Origin Resource Sharing
app.use(cors(corsOptions));
// built-in middleware to handle urlencoded form data
app.use(express.urlencoded({ extended: false }));
// built-in middleware for json
app.use(express.json());
//middleware for cookies
app.use(cookieParser());
//serve static files
app.use('/', express.static(path.join(__dirname, '/public')));
// routes
app.use('/', require('./routes/root'));
app.use('/pictures', require('./routes/api/pictures'));
app.all('*', (req, res) => {
res.status(404);
if (req.accepts('html')) {
res.sendFile(path.join(__dirname, 'views', '404.html'));
} else if (req.accepts('json')) {
res.json({ "error": "404 Not Found" });
} else {
res.type('txt').send("404 Not Found");
}
});
app.use(errorHandler);
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
//api/pictures.js
const picturesController= require('../../controllers/picturesController');
const express = require('express')
const router = express.Router();
// for POST request use app.post
router.route('/')
.post( async (req, res) => {
// use the controller to request external API
const response = await picturesController.handlePictures()
// send the response back to client
res.json(response)
})
module.exports = router;
You just need to return the result from SerpApi in your handlePictures function. To do this make a new Promise and when search.json runs callback do what you need with the results and pass it in resolve.
Your picturesController.js with an example of returning all results.
//pictures controller
const SerpApi = require("google-search-results-nodejs");
const { json } = require("express");
const search = new SerpApi.GoogleSearch(process.env.API_KEY); //your API key from serpapi.com
const handlePictures = async (req, res) => {
return new Promise((resolve) => {
const params = {
q: "Coffee",
location: "Austin, Texas, United States",
hl: "en",
gl: "us",
google_domain: "google.com",
};
const callback = function(data) {
resolve(data);
};
search.json(params, callback);
});
};
module.exports = { handlePictures };
Output:
And I advise you to change your API key to SerpApi to prevent it from being used by outsiders.
Since I don't have the full context of your App I can just assume the context. But given the fact that you already have wrapped the logic of calling the external API into a dedicated controller you can use it in the following way in an express app (used the hello world example from express):
// import your controller here
const express = require('express')
const app = express()
const port = 3000
// for POST request use app.post
app.get('/', async (req, res) => {
// use the controller to request external API
const response = await yourController.method()
// send the response back to client
res.json(response)
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Here's an example how to execute the http request from the frontend:
const response = await fetch('http://localhost:3000') // result from res.json(response)
I am trying to do a GET request in order to retrieve some images from my Cloudinary account. But when I run the server, I get a 400 status code on my UI with reading
Cannot GET /
How can I solve this issue?
const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const { json } = require('body-parser');
const axios = require('axios');
const app = express();
app.use(cors());
app.use(json());
const { parsed: config } = dotenv.config();
const BASE_URL = `https://api.cloudinary.com/v1_1/${config.CLOUD_NAME}/resources/image`;
const auth = {
username: config.API_KEY,
password: config.API_SECRET,
};
app.get('/photos', async(req, res) => {
const response = await axios.get(BASE_URL + '/resources/image', {
auth,
params: {
next_cursor: req.query.next_cursor,
},
});
return res.send(response.data);
});
app.get('/search', async (req, res) => {
const response = await axios.get(BASE_URL + '/resources/search', {
auth,
params: {
expression: req.query.expression,
},
});
return res.send(response.data);
});
const PORT = 7000;
app.listen(PORT, console.log(`Server running on port ${PORT}`));
If you open your server URL in browser you will get Cannot GET / because you don't have base route.
It's not needed in most cases, since you don't access your node server from browser, it just run's in the background.
You generally display your frontend (Angular, React) in browser.
But if you don't like the message you can add a base route.
app.get('/', (req, res) => res.send('Hello World'));
I'm not sure what are you trying to achieve, but at least you won't get this error.
I have been trying to solve this error from a long time. I could not find a similar problem online. I am sending a request through postman to twilio API for whatsapp. Everything seems ok. The promise should send a JSOM object in response but it keeps sending request until socket hangs up error occurs. Here is my code
const dotenv = require('dotenv').config();
const express = require('express');
const { response } = require('express');
const app = express();
app.use(express.json());
exports.sendMessages = function(sender, reciever, message) {
const accountSid = process.env.ACCOUNT_S_ID;
const authToken = process.env.AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
from: 'whatsapp:+'+sender,
body: message,
to: 'whatsapp:+'+reciever
})
.then(response => {
return {
data: JSON.stringify(response),
}})
.catch(e => { console.error('Got an error:', e.code, e.message); });
}
Calling the API
const express = require('express');
const app = express();
app.use(express.json());
// for parsing application/json
const send = require('./index');
let endPoint = process.env.ENDPOINT;
app.post(endPoint, function (req, res) {
send.sendMessages('14155238886', '393200149462','test message');
});
const port = process.env.PORT;
app.listen(port);
console.log('Successfully connected to ' +port);