简体   繁体   中英

How to receive Response from API in NodeJS?

I have a basic form that makes a POST request to my API(localhost:7000). The API receives my REQUEST, it inserts a new record to my database and all works fine.

Now, I want to receive a response in my Website (localhost:5000) or any custom message given from the API, so that I can do basic if-else stuff. Although, Im sending res.sendStatus(200) from my API but it redirects my Website to a blank page with the "OK" message

POST route of the API

API 的 POST 路由

Website rendering file

在此处输入图像描述

You can give back a JSON response

res.json({
”message":”some message" 
})

You can access this message using Javascript in front end.

const data = { username: 'example' };

fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => { 
if(response.message){
dosomething()
 }
 })
.catch((error) => {
console.error('Error:', error);
});

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