简体   繁体   English

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

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

What I've done: I tried to post json from angular to nodejs but it failed.我所做的:我尝试将 json 从 angular 发布到 nodejs,但失败了。 I tried to search for solution of "undefined post nodejs json" and "options instead of post", and changed my header to exclude the [option], also tried to parse the json data I tried to set, but nothing is useful.我试图搜索“undefined post nodejs json”和“options instead of post”的解决方案,并更改了我的标题以排除[option],还尝试解析我尝试设置的json数据,但没有任何用处。

The problem: In the angular code below, I did not get response, there was no output of the "console.log()", I wonder what is wrong.问题:在下面的 angular 代码中,我没有得到响应,“console.log()”没有输出,我想知道哪里出了问题。 And the json.body I reuqired in app.js returns "undefined"我在 app.js 中重新定义的 json.body 返回“undefined”

I checked the browser, first it sends [options] request and gets 200OK, but next when it sends [post], but no status is returned :我检查了浏览器,首先它发送 [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

Is there any mistake in the code?代码中是否有错误?

angular code: component.ts角度代码: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 using express: app.js 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}!`))


Because you are using Sec-Fetch-Mode: cors in your request, then your API in Express needs to have CORS enabled and configured correctly.因为您在请求中使用了Sec-Fetch-Mode: cors ,所以您在 Express 中的 API 需要启用并正确配置 CORS。 If you are doing local development, I would turn CORS off and enable it in production, but you also may be running two processes for the Angular app and the Express app.如果您正在进行本地开发,我会关闭 CORS 并在生产中启用它,但您也可能正在为 Angular 应用程序和 Express 应用程序运行两个进程。 In that case, follow the documentation for Express to enable CORS on the API via the documentation below.在这种情况下,请按照 Express 文档通过以下文档在 API 上启用 CORS。

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

I added these in my code and they appeared deprecated in the pic, but it does work我在我的代码中添加了这些,它们在图片中似乎已被弃用,但它确实有效

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