NEXTJS - fetching data from the server - javascript

I want to fetch data from the nextjs server on the front end, however the code after fetch() doesn't work in the onSubmit() function.
here is the /test page
pages/test
const onSubmit = (data) => {
console.log("________");
users.map(async (user, index) => {
if (data.email === user.email) {
if (data.password === user.password) {
console.log("hi");
const data = await fetch("http://localhost:3000/api/test");
// after the fetch, this code does not run
console.log("back-end is: ", data);
}
}
});
};
and here is my code in /api/test
export default async function student_method(req, res) {
return console.log("get in server");
}
so please what is the problem??
i'm try to get the data inside the database
so we need to use fetch() method but fetch() work succesfully but code after fetch() does not work

I think the issue is using the return statement on the server side. NextJS provides helper methods in the res object you receive in your server-side function.
Try something like this:
res.status(200).send("get in server");
For details, see here: API Routes: Response Helpers

const data = await fetch("http://localhost:3000/api/test");
The problem is that line. There you waiting a Promise resolve, but if you see you api/test you only return a log.
Please try returning a Promise.

The code is not working now because you're waiting for the server response but you aren't sending anything from the server.
You should send response to the client like this:
export default async function student_method(req, res) {
/* status code 200 or any other status codes */
res.status(200).send("get in server");
}

Related

Using Lambda with NodeJS and fetching value correctly from Dynamo db, I cannot process the json data recieved

//Function to pull data from Dynamo DB (works)
async function pullone(sessionid) {
const params = {
TableName: dynamodbTableName,
Key: {
'sessionid': sessionid
}
};
return await dynamodb.get(params).promise().then((response) => {
return response.Item
}, (error) => {
console.error('Do your custom error handling here. I am just gonna log it: ', error);
});
}
//executing it
`exports.handler = async (event) => {
let sessionid = "45883754"
let data = pullone(sessionid)
return data
};`
//The above works well and the 'data' returned is
{ "school": "3wc", "sessionid": "45883754" }
I have tried to get values with data.school but itdoes not work. Is this an issue with Lambda because this is supposed to be a nobrainer. Your support will be appreciated. Thanks guys
I tried data.school or data.sessionid but the values were not coming forth
For future posts, please show the error message or what you recieved that was unexpected.
Im your case, the Lambda function is doing an asynchronous call to fetch the data meaning that the lambda itself is asynchronous. In your code that calls the Lambda, you meed to add await such that the call looks like this:
let data = await pullone(sessionid)
console.log(data.school)

Error: Can't set headers after they are sent node.js

hi guys im fairly new to node.js and I was wonder if I am making a call twice that I am unaware of. I am getting a Error: Can't set headers after they are sent.
export const hearingReminder = functions.https.onRequest((request, response) => {
console.log(request.body)
const payload = {
notification: {
title: 'Upcoming Hearing',
body: 'You have a hearing in one hour.',
}
};
const fcm = request.body.fcm
console.log(request.body.fcm)
try {
response.status(200).send('Task Completed');
return admin.messaging().sendToDevice(fcm, payload);
} catch (error) {
return response.status(error.code).send(error.message);
}
Your code is attempting to send a response twice, under the condition that admin.messaging().sendToDevice generates an error. Instead of sending the 200 response before the call, only send it after the call. Sending the response should always be the very last thing performed in your function.
Your code should be more like this:
admin.messaging().sendToDevice(fcm, payload)
.then(() => {
response.status(200).send('Task Completed');
})
.catch(error => {
response.status(error.code).send(error.message);
})
Note that you don't need to return anything for HTTP type functions. You just need to make sure to handle all the promises, and only send the response after all the promises are resolved.

How to get a correct response from an API on AWS lambda

This is my first time soliciting the Stack-Overflow community.
Since a few days I have been learning to use the AWS lambda service connected with GETEWAY.
I need to do a GET on an API but the problem is that I constantly receive a empty response.
Here is an example of my code with a free access API:
var getApi= async function(event) {
var x = await axios.get(url)
}
var getResponse = async function(){
var data= await getApi()
if (data.status ==200){
return data
}
}
exports.handler = async function() {
return getResponse().then(res => {
const response = {
statusCode: 200,
body: JSON.stringify(res),
};
return response
}).catch(error => { return error})
};
Thank you very much for your help,
It is because of node.js asynchronous call.
Your function finishes the running before asynchronous call returns.
I fixed some lines of codes. I wish this might be helpful for you.
const getApi= async function() {
return await axios.get(url)
}
const getResponse = async function(){
const data= await getApi()
if (data.status ==200){
return data
}
}
exports.handler = async function() {
return await getResponse().then(res => {
const response = {
statusCode: 200,
body: JSON.stringify(res),
}
return response
}).catch(error => console.error(error))
}
I would suggest using console.log() all over the file to debug. You should by default be able to see the response to these console logs in Cloudwatch :)
Read more here:
https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions-logs.html
I myself ran into this issue very recently. The solution is:
If you are using the Lambda as an authorizer in your AWS Gateway, then the Lambda should return a JSON object that contains principalId, policyDocument and context.
Context is a map where you can add your own custom variables such as Strings, Numbers and Booleans.
The entire content of the JSON object will be returned to the Gateway. Check out this documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-lambda-authorizer-output.html
I also have a pretty detailed Stackoverflow post on how the Gateway should be configured via Cloudformation YAML file: AWS API Gateway with Lambda Authorizer

Append a query param to a GET request?

I'm trying to make a simple API that calls another API that will return some information. The thing is, in order to connect to the second API, I need to attach query parameters to it.
So what I've tried to do so far is to use an axios.get in order to fetch the API. If I didn't need to add queries on top of that, then this would be really simple but I'm having a really hard time trying to figure out how to attach queries on top of my request.
I've created an object that pulled the original query from my end and then I used JSON.stringify in order to turn the object I made into a JSON. Then, from my understanding of Axios, you can attach params my separating the URL with a comma.
On line 6, I wasn't sure if variables would carry over but I definitely can't have the tag var turned into the string "tag", so that's why I left it with the curly brackets and the back ticks. If that's wrong, then please correct me as to how to do it properly.
the var tag is the name of the query that I extracted from my end. That tag is what needs to be transferred over to the Axios GET request.
app.get('/api/posts', async (req, res) => {
try {
const url = 'https://myurl.com/blah/blah';
let tag = req.query.tag;
objParam = {
tag: `${tag}`
};
jsonParam = JSON.stringify(objParam);
let response = await axios.get(url, jsonParam);
res.json(response);
} catch (err) {
res.send(err);
}
});
response is SUPPOSED to equal a JSON file that I'm making the request to.
What I'm actually getting is a Error 400, which makes me think that somehow, the URL that Axios is getting along with the params aren't lining up. (Is there a way to check where the Axios request is going to? If I could see what the actual url that axios is firing off too, then it could help me fix my problem)
Ideally, this is the flow that I want to achieve. Something is wrong with it but I'm not quite sure where the error is.
-> I make a request to MY api, using the query "science" for example
-> Through my API, Axios makes a GET request to:
https://myurl.com/blah/blah?tag=science
-> I get a response with the JSON from the GET request
-> my API displays the JSON file
After looking at Axios' README, it looks like the second argument needs the key params. You can try:
app.get('/api/posts', async (req, res, next) => {
try {
const url = 'https://myurl.com/blah/blah';
const options = {
params: { tag: req.query.tag }
};
const response = await axios.get(url, options);
res.json(response.data);
} catch (err) {
// Be sure to call next() if you aren't handling the error.
next(err);
}
});
If the above method does not work, you can look into query-string.
const querystring = require('query-string');
app.get('/api/posts', async (req, res, next) => {
try {
const url = 'https://myurl.com/blah/blah?' +
querystring.stringify({ tag: req.params.tag });
const response = await axios.get(url);
res.json(response.data);
} catch (err) {
next(err);
}
});
Responding to your comment, yes, you can combine multiple Axios responses. For example, if I am expecting an object literal to be my response.data, I can do:
const response1 = await axios.get(url1)
const response2 = await axios.get(url2)
const response3 = await axios.get(url3)
const combined = [
{ ...response1.data },
{ ...response2.data },
{ ...response3.data }
]

Get request yields response with data in it, but when accessing .data specifically it yields undefined

Apologies if the terminology is not great, still new to fullstack.
Hello! I am trying to get all the users in my DB. The get() response is OK as the client is receiving the response (see image below)
The problem is that when I try to fetch the .data I get undefined.
Here's my Vue Component
import UserService from '#/services/UsersService.js'
export default {
data () {
return {
users: null
}
},
async mounted () {
// GET request for all users.
this.users = UserService.index().data
console.log('The response is OK', await UserService.index())
console.log('when trying to fetch the .data I am getting ', await this.users)
}
}
The index() function
import Api from '#/services/Api'
export default {
index () {
return Api().get('users')
}
}
Everything works fine, except that I get undefined data...
I think you forgot to fetch the data asynchronously?
async mounted () {
// GET request for all users.
- this.users = UserService.index().data
+ const res = await UserService.index()
+ this.users = res.data
console.log('The response is OK', await UserService.index())
console.log('when trying to fetch the .data I am getting ', await this.users)
}
You correctly use await syntax in the first console.log, which might explain why the data return correctly.

Categories

Resources