Hello i have two NodeJS running on my sever
please this is only a dev machine not production so i know parsing the form data etc etc
App.js - Backend Express Sever running on port 4000
index.js - Front End PUG/Express running on port 8000
i can access the frontend on something.mydomain.com
but when i try to ajax the backend with 'POST' to localhost:4000/Whatever/Whatever
it doesnt allow me to.
as in it tries to load locahost from the WWW external not internal
login.js
const serverurl = "http://localhost:4000";
$(document).ready(function () {
$('#login').click(function () {
var data = {};
data.username = $('#inputusername').val();
data.password = $('#inputpassword').val();
$.ajax({
url: serverurl+'/user/login'
, type: 'POST'
, data: JSON.stringify(data)
, contentType: 'application/json'
})
.done(function (data) {
if (data[0].response == '1') {
alert("Logged In");
Cookies.set('user', data[0].name);
Cookies.set('location', data[0].location);
Cookies.set('role', data[0].role);
$(location).attr('href', '/home');
} else if(data[0].response == '0') alert("Username or Password Incorrect")
});
});
frontend request image
Any help will be appreciated
You got CORS error. You can reach more info about it.
My solution is using for Express.js CORS package
Your main js file should be like:
// app.js
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
Related
I am trying to fetch data from my local server and here is my server and how I handled GET requests:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.listen(port, () => {
console.log(`app running on port: ${port}...`);
});
const responseToClient = (req, res) => {
res.status(200).json({
status: 'success',
body: 'Hello from the server!',
});
};
app.get('/api', responseToClient);
When I run my server and send a GET request to this address: 127.0.0.1:3000/api with Postman, it works perfectly.
The thing is I created a html page along with a js file and want to fetch data from my local server by it. Here is my fetch request on my js file:
const url = '/api';
const fetchData = async () => {
try {
const response = await fetch(url);
const body = await response.json();
alert(body);
} catch (error) {
alert(error);
}
};
fetchData();
I run my html file with live-server (extension) which runs on port 5500 by default , so the address my fetch request goes to will be 127.0.0.1:5500/api (instead of 127.0.0.1:3000/api), so it does not exists and I get an error message.
I tried to change the port of my server and set it to 5500 (the same as live-server) but it did not work.
How can I run my local server and send requests to it with live-server and my html file?
Solved by using:
const url = 'http://localhost:3000/api';
instead of the ip address and installing cors middle ware.
If you do not want to have the HTML and JS files static-ed onto your Express server, then try this:
const url = '/api'; // bad
const url = '127.0.0.1:3000/api'; // better
I am new to fullstack development and I want to deploy a project that will be used on the same network by different users. I have used angular for the front-end and node/express and MySQL for the backend. Before proper deployment, for testing purposes, I am accessing my application from another computer that is on the same network. The application, however, is throwing an error when I try to login.
VM12:1 POST http://localhost:3000/auth net::ERR_CONNECTION_REFUSED
Here's my backend code:
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mysqlConnection = require('./connection');
const routes = require('./routes');
const http = require('http');
const path = require('path');
var app = express();
app.disable('x-powered-by');
app.use(express.static(__dirname + '/dist'));
app.get('/*', (req, res) => res.sendFile(path.join(__dirname)));
app.use(cors());
app.use(bodyParser.json());
app.use(routes);
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port, '0.0.0.0', () => console.log(`Running on port ${port}`));
routes.js
router.post("/auth", (req, res) => {
var email = req.body.email;
var password = req.body.password;
var accessBasic = "Basic";
var accessPremium = "Premium";
mysqlConnection.query("SELECT * FROM authorization WHERE email = ? AND password = ?", [email,
password], (err, results) => {
if(!err)
{
var myJSON = JSON.stringify(results);
var check_email = myJSON.search(/email/i);
var check_password = myJSON.search(password);
var check_access = myJSON.search(accessBasic);
var check_access2 = myJSON.search(accessPremium);
if ((check_email != -1) && (check_password != -1) && (check_access != -1))
{
res.send("Successfully Authorized to Basic Access");
}
else if ((check_email != -1) && (check_password != -1) && (check_access2 != -1))
{
res.send("Successfully Authorized to Premium Access");
}
else
{
res.send("Authorization failed");
}
}
else
{
console.log("Connection to authorization failed: " + err.message);
}
})
})
I have allowed incoming connections in my firewall and done everything but, couldn't find the reason why my endpoint is refusing to connect while trying to connect on device other than my system on the same network. I don't know what's wrong. Anybody has any idea what am I doing wrong? I have hosted my application on my system and accessing it from another on the same network.
EDIT: Since, this question has gained quite a lot of views, I would like to mention that I didn't change any of the firewall settings as mentioned above. All the default firewall settings of the Windows OS were used. I just deployed the app and ran it.
ANSWER: I was having an issue on the front-end. I was targeting localhost instead of the IP address of the system that the app was hosted on. See my answer below for the details.
For anyone who is going to see this in future. I was having an error on my front-end. Instead of calling http://localhost:3000/name-of-my-api-endpoint, I changed the localhost to the IP address of my system and then ran ng build --prod again in order to make new static files and serve them from node.js.
I have experienced the same issue with MongoDB
I have found out that the problem was my MongoDB wasn't connected to my localhost and the issue was related to tokens and authentication.
So I went to my terminal on my backend folder and ran the command -
npm install dotenv --save
Then I created my .env file located in my backend folder
and added the following commands
PORT=3000 APP_SECRET="RANDOM_TOKEN_SECRET"
MONGODB="mongodb+srv://youruser:yourpassword#cluster0.k06bdwd.mongodb.net/?retryWrites=true&w=majority"
Then called it in my app.js file
const dotenv = require("dotenv");
dotenv.config();
mongoose.connect(process.env.MONGODB,
{ useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB!'))
.catch(() => console.log('Failed to connect to MongoDB !'));
module.exports = app;
Finally I have added it in my backend/controllers/user.js
const token = jwt.sign(
{userId: user._id},
process.env.APP_SECRET,
{expiresIn: '24h'});
res.status(200).json({
userId: user._id,
token: token
});
You can access your app in the same network from your #IP not from localhost (127.0.0.1) change it to 192.168.1.X (your local #IP address) and make sure to changed it in your .env file.
don't understand what's wrong with my server and code. I am passing tutorial and did everything just like in the video but still have the problem
Image
It seems like you are using https connection without handling TLS certificates passing.
Here is a code snippet to make you access your openweathermap API without configurating certificates.
const express = require('express')
const https = require('https')
const app = express()
app.get("/", function(req, res) {
const url = "<openweathermap>"
var options = require('url').parse( /**String*/ url );
options.rejectUnauthorized = false;
https.get(options, function(response) {
console.log(response);
}).on( 'error',function ( e ) {
console.log(err);
}).end();
res.send("Sever up and running");
}
app.listen(3000, function(){
console.log("Server running on port 3000";
}
I would suggest to read more on how to setup certificates for HTTPS in Node.JS,
refer this doc. for more details.
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.
I'm want to get data from the node/express server after send ajax query from any page of the nuxtjs app.
Usually, for getting and sending ajax query in PHP server, I'm do like this $_GET['var']; echo json_encode('Server got data');
Now I want to use node server express for saving data in mongodb.
When I trying to send a query, response return full code of file test.js.
File index.vue
methods: {
onServer() {
this.$axios.get('/server/test').then(res => {
console.log('res', res.data)
})
}
}
File test.js
var express = require('express');
var app = express();
app.get('*', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
File server/index.js
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = !(process.env.NODE_ENV === 'production')
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
} else {
await nuxt.ready()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
I'm a new user node, please help me!
Your main issue is that you are targeting "test.js" in your axios url. This is why it responds with the file rather than what the get route should respond with.
So try with:
this.$axios.get('http://nuxt-profi/server/test').then(...
and see what you get. You should also be able to access that in the browser, just go to your url http://nuxt-profi/server/test and it should show your "Hello World" reponse.
However I can't be sure how you have set all this up. Are you running this as development? In which case maybe you should access it as http://localhost:3000/server/test but maybe you have virtual hosts configured like this. Also, is this a separate backend api or are you trying this as server middleware?
If this doesn't help please give us more info about your project setup and we'll go from there.