簡體   English   中英

Express/Nodejs 使用 post 方法從 angular 接收到未定義的 json

[英]Express/Nodejs received undefined json from angular using post method

我所做的:我嘗試將 json 從 angular 發布到 nodejs,但失敗了。 我試圖搜索“undefined post nodejs json”和“options instead of post”的解決方案,並更改了我的標題以排除[option],還嘗試解析我嘗試設置的json數據,但沒有任何用處。

問題:在下面的 angular 代碼中,我沒有得到響應,“console.log()”沒有輸出,我想知道哪里出了問題。 我在 app.js 中重新定義的 json.body 返回“undefined”

我檢查了瀏覽器,首先它發送 [options] 請求並獲得 200OK,但是接下來當它發送 [post] 時,但沒有返回任何狀態:

OPTIONS /api/postData HTTP/1.1
Host: 127.0.0.1:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://127.0.0.1:4200/
Origin: http://127.0.0.1:4200
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
POST http://127.0.0.1:3000/api/postData
Host: 127.0.0.1:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Content-Length: 27
Origin: http://127.0.0.1:4200
Connection: keep-alive
Referer: http://127.0.0.1:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site

代碼中是否有錯誤?

角度代碼:component.ts

this.http.post<any>("http://127.0.0.1:3000/api/postData", loc_json).subscribe(response =>{
      console.log("Post to nodejs from angular")
      console.log(response);
    }); 

nodejs 使用 express:app.js

const express = require('express')
const api_helper = require('./API_helper')
const port = 3000
const cors = require('cors')
const app = express()
app.use(cors())


// allowCrossDomain = function(req, res, next) {
//     res.header('Access-Control-Allow-Origin', '*');
//     res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
//     res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
//     if ('OPTIONS' === req.method) {
//       res.send(200);
//     } else {
//       next();
//     }
//   };
  
// app.use(allowCrossDomain);

app.get('/', (req, res, next) => {
    res.send("wtffffffffffffffffff");//send to the page
})

app.post('/getAPIResponse', (req, res, next) => {
    api_helper.make_API_call('https://jsonplaceholder.typicode.com/posts')
    .then(response => {
        res.json(response)
    })
    .catch(error => {
        res.send(error)
    })
})

//angular --> nodejs
app.post('/api/postData', function(request, response){
    //console.log("postData on nodejs 3000");
    // const loc_nodejs = req.body;
    // console.log("loc_nodejs.loc ", loc_nodejs); 
    console.log(request.body);  
    
})

app.listen(port, () => console.log(`NodeJS App listening on port ${port}!`))


因為您在請求中使用了Sec-Fetch-Mode: cors ,所以您在 Express 中的 API 需要啟用並正確配置 CORS。 如果您正在進行本地開發,我會關閉 CORS 並在生產中啟用它,但您也可能正在為 Angular 應用程序和 Express 應用程序運行兩個進程。 在這種情況下,請按照 Express 文檔通過以下文檔在 API 上啟用 CORS。

https://expressjs.com/en/resources/middleware/cors.html

我在我的代碼中添加了這些,它們在圖片中似乎已被棄用,但它確實有效

const bp = require('body-parser');
app.use(bp.json())
app.use(bp.urlencoded({ extended: true }))\

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM