I'm using both Ubuntu and Visual Studio Code to launch my server program, they were both sucessfully taking and sending back replies from Postman a few days ago. The server code runs fine, and says the server is up and running at https://loccalhost:8080
But when I try to send a GET request from Postman, I get this error from Postman:
This is the environment I'm using:
And this is the error I get from my server program when it gets a request:
How ther server is configured:
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.set("port", 8080);
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
const Pool = require("pg").Pool;
const config = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: "taskfour"
};
const pool = new Pool(config);
//HELLO WORLD
app.get("/hello", (req, res) => {
res.json({msg: "Hello, World!"});
});
app.listen(app.get("port"), () => {
console.log(`Find the server at http://localhost:${app.get("port")}`);
});
The server had previously been working fine, Postman was sending requests, doing tests, and my code was passing them. I didn't change much in the meanwhile, I'm not sure what changed. I've tried turning off my proxy server on Postman, but it hasnt' helped. Any help would be greatly appreciated.
Looks like the HTTP listening code is missing, for example:
app.listen(8080, function () {
console.log('App listening on port 8080.');
});
Wow, I didn't realize the postgres service wasn't running. I just needed to enter the command "sudo service postgresql start" in my terminal, and the requests work again.
Related
First a quick preface I think may be helpful: I am new to splitting my client and server into separate web apps. My previous apps have all had my server.js at the root level in my directory and the client (typically a create-react-app) in a /client folder.
What I wanted to do: Host a single express.js server on the web which multiple other web applications could make requests to.
I did the first part using an express server and aws elastic beanstalk.
server.js
require('dotenv').config()
const express = require('express');
const app = express();
const cors = require('cors');
const PORT = process.env.PORT || 5000;
const Mongoose = require('mongoose');
const { Sequelize } = require("sequelize");
//ROUTES
const APIUser = require('./routes/api/mongo/api-user');
more routes...
//INITIATE DATA MAPPING CONNECTIONS START
Mongoose.connect(
process.env.MONGO_URI,
{ useNewUrlParser: true, useUnifiedTopology: true },
console.log("connected to MongoDB")
);
const Postgres = new Sequelize(process.env.PG_CONN_STRING);
try {
Postgres.authenticate()
.then(console.log("connected to Postgres"));
} catch {
console.log("Postgres connection failed")
}
//INITIATE DATA MAPPING CONNECTIONS END
//middleware
app.use(cors())
more middleware...
//home route
app.get('/api', (req, res) => {
console.log('RECEIVED REQ to [production]/api/')
res.status(200).send('models api home').end();
})
//all other routes
app.use('/api/user', APIUser);
more route definitions...
//launch
app.listen(PORT, () => console.log(`listening on port ${PORT}`));
The log file for successful boot up on aws: https://imgur.com/vLgdaxK
At first glance it seemed to work as my postman requests were working. Status 200 with appropriate response: https://imgur.com/VH4eHzH
Next I tested this from one of my actual clients in localhost. Here is one of my react client's api util files where axios calls are made to the backend:
import { PROXY_URL } from '../../config';
import { axiosInstance } from '../util';
const axiosProxy = axios.create({baseURL: PROXY_URL}); //this was the most reliable way I found to proxy requests to the server
export const setAuthToken = () => {
const route = "/api/authorization/new-token";
console.log("SENDING REQ TO: " + PROXY_URL + route)
return axiosProxy.post(route)
}
export const authorize = clientsecret => {
const route = "/api/authorization/authorize-survey-analytics-client";
console.log("SENDING REQ TO: " + PROXY_URL + route)
return axiosProxy.post(route, { clientsecret })
}
Once again it worked... or rather I eventually got it to work: https://imgur.com/c2rPuoc
So I figured all was well now but when I tried using the live version of the client the request failed somewhere.
in summary the live api works when requests are made from postman or localhost but doesn't respond when requests are made from a live client https://imgur.com/kOk2RWf
I have confirmed that the requests made from the live client do not make it to the live server (by making requests from a live client and then checking the aws live server logs).
I am not receiving any Cors or Cross-Origin-Access errors and the requests from the live client to the live server don't throw any loud errors, I just eventually get a net::ERR_CONNECTION_TIMED_OUT. Any ideas where I can look for issues or is there more code I could share?
Thank you!
Add a console.log(PROXY_URL) in your client application and check your browser console if that's logged correctly.
If it works on your local client build, and through POSTMAN, then your backend api is probably good. I highly suspect that your env variables are not being set. If PROXY_URL is an emplty string, your axios requests will be routed back to the origin of your client. But I assume they have different origins since you mention that they're separate apps.
Remember environment variables need to prefixed with REACT_APP_ and in a production build they have to be available at build time (wherever you perform npm run build)
hy, I'm learning nodeJS but when do post using postman data is saving in db but not displaying response in POSTMAN. On postman just displaying sending request... .
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
app.listen(8000, ()=>{
console.log('Server is running on port:8000')
})
I don't think you're even running on a port, it says here
console.log('Server is running on port:8000')
})
All you do is console.log Server is running on Port 8000 with no back tick, therefore your not even running your server. This is why I think your Code is not working, test it out and see, if you get an error then you can debug from there. At least put some effort into debugging rather than immediately going on stack overflow. replace what you done with the port with this
// Create a variable called port and set it to your desired port
const port = 8000;
// Then hook it up to express.
console.log(`Server is running on port: ${port}`)
})
If the problem is still there then I think I have the solution to it
Check if you have mongoose and express installed
(it's npm i mongoose express)
I don't think you're even connected to your mongoose server, try doing this
const express = require("express")
const app = express()
// dbConnection
require('./mongo')
// Models
require('./model/Post')
// MIDDLEWARE
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const mongoose = require('mongoose')
const Post = mongoose.model("Post")
// Hook it up to res
const port = 8000
// POST REQUEST
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
res.status(500)
}
})
// Mongoose Connection
mongoose
.connect("your connection (it should be connection to application on mongo)", {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: true
})
.then(() => {
console.log("Connected to the database");
})
.catch((err) => {
console.log(err);
});
app.listen(8000, ()=>{
console.log(`Server is running on port: ${port}`)
})
Then once you've finished that, you established a connection to the mongodb server and should send the request to post
I think the catch block is executed. In this block, you only set the status of the response to 500 but you don't actually send the response to the client. That's why the Postman screen keeps blocking.
So, there are 2 things:
you need to send something to the client
you need to log the error to debug.
app.post('/posts', async (req, res)=>{
// res.send(req.body)
try{
const post = new Post()
post.title = req.body.title
post.content = req.body.content
data = await post.save()
res.json(data)
}catch(error){
console.log(error);// for debugging
res.status(500).send("ERROR_SERVER"); // send something to client
}
})
I have found the answer for your error, as I said in my old answer, running your tests would've worked, and showed you the error, however I have found the answer, I am assuming you have already found the solution (which is probably the same solution as mine) but if you haven't here's the problem.
The problem
It's very simple, you're creating a variable for mongoose after you required mongoose require('./mongo'); const mongoose = require('mongoose') This is wrong as JavaScript and most programming languages read code line by line (if not then all) so change this up to be instead the following:
Solution
const mongoose = require('mongoose');
require('./mongo');
Information
Create the variable before you require the package like so (in your code example):
const mongoose = require('mongoose');
require('./mongo');
If you have more problems
If you do have more problems then try to reinstall/update the package dependency for mongoose as following:
yarn add mongoose
or
npm install mongoose
If you do still have problems after the only think I can ask you to do is to change the line of code when it says
require('./mongo');
to either
require('./{filename}'); // Whatever the actual filename is.
or:
require('./mongoose');
Tips to improving your question
Even if my question doesn't work for your code make sure to paste the error message or the important parts of the error message into the question, otherwise this makes it hard to pinpoint what your error is. This makes it easier to find the solution for your code.
Sorry for this noob question, student here and still learning
I'm trying to pass the request body of a POST request from server to client. I have an Arduino sensor making post requests with sensor data to an express server. The sensor data is inside the POST request body, and I push the data to an array called 'dataArray'. This part seems to be working.
My problem is that I'm now stuck on how to pass this data from the express server to a Vue component on the client side. Should I make a new route? I'm not asking anyone to write any code for me, I'm just hoping someone could point me in the right direction or suggest something, because I'm at a loss on exactly how I should go about doing this. Thank you.
server.js
var express = require("express")
var cors = require("cors")
var bodyParser = require("body-parser")
var app = express()
var mongoose = require("mongoose")
var Users = require("./routes/Users")
var port = process.env.PORT || 5000
var dataArray = []
app.use(bodyParser.json())
app.use(cors())
app.use(bodyParser.urlencoded({ extended: true }))
const mongoURI = 'my_connection_string'
mongoose.connect(mongoURI, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err))
app.use("/users", Users)
app.route("/api/:apikey1")
app.post("/api/:apikey1", function(request, response) {
var myData = request.body;
console.log(myData)
dataArray.push(myData)
response.send("Array Filled")
});
app.listen(port, function () {
console.log("Server is running on port: " + port)
})
If you want to keep it simple use the socket.io library.
It is available for both client and server, you can use in your Vue client too.
Also, you won't need any extra route, just in your app.post("/api/:apikey1") route, use the emit method on socket.io library to broadcast the data as it is received from the sensors
Any data flow from the server to client must be first initiated on the client side, either by polling, using WebSockets or Server-sent events.
Here's my app.js file.
var express = require('express'),
bodyParser = require('body-parser'),
oauthServer = require('oauth2-server'),
oauth_model = require('./app_modules/oauth_model')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }));
var jsonParser = bodyParser.json();
app.oauth = oauthServer({
model: oauth_model, // See below for specification
grants: ['password', 'refresh_token'],
debug: process.env.OAUTH_DEBUG,
accessTokenLifetime: 172800,
refreshTokenLifetime: 172800,
authCodeLifetime: 120,
});
// Oauth endpoint.
app.all('/oauth/token', app.oauth.grant());
// User registration endpoint.
app.post('/users', jsonParser, require('./routes/register.js'));
// Get user details.
app.get('/users', app.oauth.authorise(), require('./routes/users.js'));
app.post('/', app.oauth.authorise(), require('./routes/test.js'));
app.use(app.oauth.errorHandler());
app.listen(3000, function () {
console.log('Mixtra app listening on port 3000!')
})
When I send an invalid json body with POST request to localhost:3000/users the request goes to register.js and the validation code works there.
but strangely when I send valid JSON body, it says "Cannot POST /users" with a 404 Not Found HTTP status code and nothing in terminal log.
Note: I'm using postman to send the api requests.
It would be really great if someone could help me with this.
Thanks,
Joy
I don't see you using the jsonParser
You should use it before sending any json to it
app.use(jsonParser);
I'm trying to send data using vue.js to my node.js server, but the browser console keeps showing me a 404: POST http://127.0.0.1:63342/myaction 404 (Not Found)
vue.js:
this.$http.post('http://127.0.0.1:63342/myaction', this.formData).then(response => {
console.log(response.body);
}
node.js:
var express = require('express');
var bodyParser = require('body-parser');
var exp = express();
exp.use(bodyParser.urlencoded({extended: true}));
exp.post('/myaction', function (req, res) {
res.send('saved: "' + req.body.name + '".');
});
exp.listen(63342, function () {
console.log('Server running at', this.address());
});
When I start my server, it says it's running at { address: '::', family: 'IPv6', port: 63342 }
The POST worked without vue.js, by simply submitting a HTML form, but now AJAX doesn't wordk. I tried multiple ports and folders, but can't figure out the mistake.
I finally figured it out. You have to manually add an address to the listener:
app.listen(63342, '127.0.0.1', function () {}
And in my case I was using the same port for API and Frontend, I had to switch ports and allow CORS