简体   繁体   English

从 node.js 发送一个简单的 json 到 index.html

[英]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我想向我的 index.html 发送一个简单的 json 消息/文件

Node.js code Node.js 代码

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现在在我的 javascript 代码中

$.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???为什么我的 Json 消息不显示??? How can I get this data and console.log it.我怎样才能得到这个数据和 console.log 它。 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.错误地实现了以下两个片段让我相信 OP 并不完全理解路由、路由器和 Express 应用程序。

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. Express 应用程序然后使用该路由器来适当地处理请求。

To define a route that will return 'hello world' to your axios request you want to rewrite your route to:要定义将“hello world”返回到您的 axios 请求的路由,您需要将路由重写为:

router.get('/',  (req, res) => {
    res.json({message: 'hello world'})
})

I use Express CORS Middleware and do not experience this issue.我使用Express CORS 中间件并且没有遇到此问题。

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:您还可以为 jQuery.ajax 显式设置一些 AJAX 选项:

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

You might also try the success option for jQuery.ajax.您也可以尝试 jQuery.ajax 的success选项。

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.我检查了 Miapl​​acidus 服务器代码和 ajax 调用都工作正常,但如果我添加了数据格式类型 json,如下所示。

$.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 请求中确保它是一个 GET 请求并且 url 是完整的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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