简体   繁体   中英

Send a simple json from node.js to index.html

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.

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'})
})

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.

You just need to change your code from:

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

to

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

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'
});

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);
  },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM