0

This should be a simple solution but when I Google it everyone seems to miss this. I want to send a simple json message/file to my index.html

Node.js code

const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();

router.get('/',function(req,res){
res.setHeader('Access-Control-Allow-Origin', '*');
res.sendFile(path.join(__dirname+'/index.html'));


}); 

app.get('/index.html', function(req, res, next) {
res.json({ message: 'Hello World' });
});

app.use('/', router);
app.listen(process.env.port || 3000);

console.log('Running at Port 3000');

Now inside my javascript code I have

$.ajax({
url: 'http://localhost:3000/',
complete: function(data) {
console.log(data);   <---------THIS IS WHERE I WANT THE JSON TO BE I 
WANT TO LOG 
IT

}
});

How come my Json message doesn't show up??? How can I get this data and console.log it. I appreciate any help I can get on this. I am using Express.

15
  • 1
    I'm confused, are you using your default route to both serve your html, and also to return json data to ajax? Why not separate them. Commented Feb 28, 2020 at 20:14
  • well, i don't see any issue with your code, do you not get anything in the log? also, if remove your sendfile Commented Feb 28, 2020 at 20:19
  • @SpeedOfRound Sorry for the confusion. But what I want to do is send the json to my ajax, so that I can CONSOLE.LOG it Commented Feb 28, 2020 at 20:19
  • @SunilLama I Can't CONSOLE.LOG the json Commented Feb 28, 2020 at 20:19
  • @MattQuaine, i just ran your code and it is giving me the log... Commented Feb 28, 2020 at 20:20

5 Answers 5

1

Having the following two snippits incorrectly implemented leads me to believe the OP doesn't fully understand routes, routers and an Express app.

router.get('/',function(req,res){
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.sendFile(path.join(__dirname+'/index.html'));
}); 

app.get('/index.html', function(req, res, next) {
    res.json({ message: 'Hello World' });
});

A router is used to define accessable routes which are expected to return useful information. An Express app then uses that router to serve requests appropriately.

To define a route that will return 'hello world' to your axios request you want to rewrite your route to:

router.get('/',  (req, res) => {
    res.json({message: 'hello world'})
})
Sign up to request clarification or add additional context in comments.

Comments

0

I use Express CORS Middleware and do not experience this issue.

const express = require('express');
const cors = require('cors');
const app = express();
const path = require('path');
const router = express.Router();

router.get('/',function(req, res){
  res.json({foo: 'bar'});

}); 

app.use(cors())
app.use('/', router);
app.listen(process.env.port || 3000);

console.log('Running at Port 3000');

You can also explicitly set some AJAX options for jQuery.ajax:

$.ajax({
  url: 'http://localhost:3000/',
  type: 'GET', 
  complete: function(data) {
    console.log(data);
  },
});

You might also try the success option for jQuery.ajax.

3 Comments

Have you tried using Postman (postman.com) to see if the request works first? Then, can you show what your browser's developer tools say is the error? In Chrome this is CTRL + SHIFT + I > Network > XHR.
NOOOOOO THAT DOES NOT SOLVE MY PROBLEM
It is definitely the correct steps to identify your problem. Highly recommend checking out Postman to test your API endpoints outside the browser first, then next test in the browser with Developer Tools. Otherwise you are operating blind.
0

You just need to change your code from:

res.send({"foo": "bar"});

to

res.json({"foo": "bar"});

1 Comment

I made the change IT DID NOT WORK BUT THANKS
0

I checked the Miaplacidus server code and ajax call both working fine, but in case i added data format type json as below.

$.ajax({
  url: 'http://localhost:3000/',
  data: {
    format: 'json'
  },
  error: function(jqXHR, textStatus, errorThrown) {
    console.log(textStatus, errorThrown);
  },
  success: function(data) {
    console.log(data);
  },
  type: 'GET'
});

Comments

0

I might be missing something here but try

app.get('/index.html', function(req, res, next) {
res.json({ message: 'Hello World' }).end();
});

and in the $.ajax request make sure its a GET request and the url is complete

$.ajax({
  url: 'http://localhost:3000/index.html',
  type: 'GET', 
  complete: function(data) {
    console.log(data);
  },
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.