I am trying to fetch data from the server to my flutter app. This is my server side code in Node.js:
const express=require('express');
const app=express();
app.use(express.json());
const getres='himu you got the request';
app.post('/post',async(req,res,next)=>{
const name= req.body.name;
console.log(name);
next();
}
);
app.get('/get',async(req,res,next)=>{
res.end('hello world');
res.json('hey from nodejs');
next();
}
);
app.listen(3000);
This is my flutter code where I am trying to fetch a string from the server but the string is returning null when I am printing in the flutter console.I am confused what should be my DOMAIN
.
const PROTOCOL = "http";
const DOMAIN = "localhost:3000";
Future<RequestResult> http_get(String route, [dynamic data]) async
{
var dataStr = jsonEncode(data);
var url = "$PROTOCOL://$DOMAIN/$route?data=$dataStr";
var result = await http.get(url);
return RequestResult(true, jsonDecode(result.body));
}
Here I am trying to print the data
Future<void> getdata() async {
var result= await http_get('get');
print(result.data);
}
As seen, there is no problem with domain, try removing the query parameter in the url variable
const PROTOCOL = "http";
const DOMAIN = "localhost:3000";
Future<RequestResult> http_get(String route, [dynamic data]) async
{
var dataStr = jsonEncode(data);
var url = "$PROTOCOL://$DOMAIN/$route?data=$dataStr";
var result = await http.get(url);
return RequestResult(true, jsonDecode(result.body));
}
Here your query parameter ?data=$dataStr
is not availabe as you have only set the routes not the queries in the backend.
You can send your get request to /get
route
When you say the server is it on your local machine on which your flutter is also running
if yes, then your domain is localhost:3000
else domain name is IP of the server where your Node code is hosted and running, (if you have DNS masked with IP, you can you use something like http://myserver.com , myserver is the domain name you masked hypothetically)
if your flutter app is running on mobile device and nodeJs on the local machine, you will need to be on the same network with your machine to access localhost:3000
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.