简体   繁体   中英

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. 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.

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. And the json.body I reuqired in app.js returns "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 /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

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

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. 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. In that case, follow the documentation for Express to enable CORS on the API via the documentation below.

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

在此处输入图片说明

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