Reputation:
I'm new to web design and am trying to create and a simple local server and a local client. I fear I have fallen down the rabbit hole as I'm going round in circles.
I have made a simple Express node.js server:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var port = 3000;
app.listen(port, function() {
console.log("Listening on port: " + port);
});
app.get('/', function(req, res) {
console.log(req);
res.send('Get request received at "/"');
});
app.post('/quotes', function(req, res) {
console.log(req);
// do something
});
and I have a javascript client:
const url = "http://localhost/3000";
fetch(url)
.then((resp) => resp.json())
.then(function(response) {
let data = response.results;
console.log(data);
//do something
})
.catch(function(error) {
console.log(JSON.stringify(error));
});
called from an index.html file.
When I type http://localhost:3000 into my (chrome) browser I get
'Get request received at "/"'
displayed in the browser and a very long req displayed in the node.js console just as I expect.
However when I load the index.html into the browser it doesn't work.
Originally the index.html file was in a different directory to the node.js server and I got the error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
So I moved it into the same directory as the node.js server and now get this error:
Failed to load resource: net::ERR_CONNECTION_REFUSED in the browser console and no output in the node console.
Upvotes: 0
Views: 617
Reputation:
Seems I needed to enable cors on my server. npm install cors and this answer solved my problem. How to allow CORS?
Upvotes: 1
Reputation: 784
I would replace
const url = "http://localhost/3000";
with const url = "http://localhost:3000";
Upvotes: 0