簡體   English   中英

從 node.js 發送一個簡單的 json 到 index.html

[英]Send a simple json from node.js to index.html

這應該是一個簡單的解決方案,但當我谷歌它時,每個人似乎都錯過了這一點。 我想向我的 index.html 發送一個簡單的 json 消息/文件

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

現在在我的 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

}
});

為什么我的 Json 消息不顯示??? 我怎樣才能得到這個數據和 console.log 它。 我很感激我能得到的任何幫助。 我正在使用快遞。

錯誤地實現了以下兩個片段讓我相信 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' });
});

路由器用於定義期望返回有用信息的可訪問路由。 Express 應用程序然后使用該路由器來適當地處理請求。

要定義將“hello world”返回到您的 axios 請求的路由,您需要將路由重寫為:

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

我使用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');

您還可以為 jQuery.ajax 顯式設置一些 AJAX 選項:

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

您也可以嘗試 jQuery.ajax 的success選項。

您只需要更改您的代碼:

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

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

我檢查了 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'
});

我可能在這里遺漏了一些東西,但請嘗試

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

並在 $.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