I'm trying to send JavaScript data to my NodeJS server - javascript

So I'm trying to send geolocation data to NodeJS via a POST request but when I console log the data in my NodeJS code it just shows an empty object.
I tested it already with postman and I can receive the data without a problem. I think the problem resides in the client side of my app
//**This is in the client Side(pure JS);
async function getWeather(position){
let coords ={
lat: position.coords.latitude,
long: position.coords.longitude
}
const options = {
method: "POST",
body: JSON.stringify(coords),
headers: {
"Content-Type": "aplication/json"
}
};
let response = await fetch("http://localhost:3000/weather", options);
let location = await response.json();
}
.
//**This is in the server side
app.post('/weather',(req,res)=>{
let coords = req.body;
console.log(coords); //This shows an empty object
res.sendStatus(200);
});

On your client side you can try this code. You can replace the url with your endpoint and try to fetch the result. As shown below, I'm getting the response back in data after executing the script.
I hope this helps.
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({lat: 10, long: 20})
});
const content = await rawResponse.json();
console.log(content);
})();

Related

Error 400 when using GPT API (in JavaScript)

I keep getting a 400 Error when I try to run my very basic chatbot using the GPT API:
error
Attached is my code; am I doing something wrong with the API key?
const chatHistoryContent = document.querySelector("#chat-history-content");
const chatMessageInput = document.querySelector("#chat-message-input");
const chatMessageSubmit = document.querySelector("#chat-message-submit");
chatMessageSubmit.addEventListener("click", async function () {
const message = chatMessageInput.value;
chatMessageInput.value = "";
// Add the user's message to the chat history
const userMessageDiv = document.createElement("div");
userMessageDiv.innerHTML = `You: ${message}`;
chatHistoryContent.appendChild(userMessageDiv);
// Use the OpenAI GPT-3 API to get a response from the chatbot
const response = await getResponseFromAPI(message);
// Add the chatbot's response to the chat history
const chatbotMessageDiv = document.createElement("div");
chatbotMessageDiv.innerHTML = `Max: ${response}`;
chatHistoryContent.appendChild(chatbotMessageDiv);
});
async function getResponseFromAPI(message) {
const apiKey = "sk-myapikey";
const endpoint = `https://api.openai.com/v1/engines/davinci/jobs`;
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": `application/json`,
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: "test prompt",
temperature: 0.5,
max_tokens: 512,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
});
const data = await response.json();
return data.choices[0].text;
}
Thanks
I have tried consulting many websites to see solutions to this but have had no luck.
400 (Bad Request) error code typically means that client request's data is incorrect. So yes, must be something with your auth headers/body of request. Quite often response contains a reason, please try to print the text of response (before trying to get json output), e.g.
console.log(response.text());
or just check Network Tab in Dev Console
You are almost there, you just have the wrong endpoint. If you change that your code will work.
The correct endpoint:
https://api.openai.com/v1/completions
I tested it with your code and it worked. Here is your code rewritten with the correct endpoint.
async function getResponseFromAPI(message) {
const apiKey = "sk-myapikey";
const endpoint = `https://api.openai.com/v1/completions`;
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": `application/json`,
"Authorization": `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: "test prompt",
temperature: 0.5,
max_tokens: 512,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
})
});
const data = await response.json();
return data.choices[0].text;
}
Source: https://platform.openai.com/docs/api-reference/completions/create

How to send a webhook using Office Script?

I need to connect Excel to Zapier through a webhook but can't make it work so far. I manage to send a webhook using this code but don't receive any data in the body.
function sendMessage() {
var request = new XMLHttpRequest();
request.open("POST", "https://hooks.zapier.com/hooks/catch/2251620/bv6gjw6/");
request.setRequestHeader('Content-type', 'application/json');
var content = { "value1": "test data" };
request.send(JSON.stringify(content));
}
sendMessage()
}```
Tried every code snippet out there but couldn't make it work. Pasted JSON data as well.
I've found the culprit - mode: 'no-cors'needs to be added. Here's the end result, you can send webhooks from Excel Script with that:
async function main(workbook: ExcelScript.Workbook) {
async function sendWebhook(data:string) {
let response = await fetch('https://hooks.zapier.com/hooks/catch/2251620/bv6gjw6/', {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: data,
});
return response;
//const json = await response.json();
//return json;
}
let data = JSON.stringify({ message: 'Hello, Excel!' });
let response= await sendWebhook(data);

Error trying to POST request from react to nodeJS

I'm trying to post a new object to my mongodb collection which is handled on my backend server, but the values from my request body are not passed to it.
I can guarantee that the object is created. The problem is that all the object values are empty.
I also guarantee that the nodejs code works correctly. The first thing I did was create a web application just using nodeJS and from that page I can create a new object normally.
But now I'm creating a frontend page using react and I'm not sure why my frontend page's post request doesn't work as intended
react code:
const handleSubmit = async (event) => {
event.preventDefault();
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name:nome,
cnpj:cnpj,
email:email,
number:telefone,
seguradora:[seguradora],
index:765756
})
};
try{
const response = await fetch('http://localhost:3001/corretoras',requestOptions)
const data = await response.json()
console.log(data)
console.log(requestOptions.body)
}
catch(error){
console.log('error trying to post',error)
}
};
nodeJS code:
router.post('/',async(req,res)=>{
const lastIndex = await Corretora.find().sort({index:-1}).limit(1).index
const corretora = new Corretora({
name:req.body.name,
cnpj: req.body.cnpj,
email:req.body.email,
number:req.body.number,
seguradora:req.body.seguradora,
index: lastIndex
})
try{
const novaCorretora = await corretora.save()
res.redirect('corretoras/'+novaCorretora.id)
}
catch{
renderNewPage(res,corretora,true)
}
})
console log from react code:
Found my issue. I didn't type app.use(express.json()) in my server.js

SyntaxError: Unexpected token r in JSON at position 0 on reactjs login page

I have been trying to make a login page in reactjs but it's throwing me an error in console like
SyntaxError: Unexpected token r in JSON at position 0 but I got 200 status code in network tab and also I'm getting "redirect" in both response and preview tab under the network tab.
I tried the same code(except it was if(response.ok) this time) with another server of my friend and it successfully redirects it to another page
This is the code that I've been trying: is response.data not correct for reactjs?
performLogin = async () => {
var body = {
password: this.state.password,
email: this.state.email
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(response); //nothing is showing in console for this statement
if (response.data == "redirect") {
this.props.history.push(`/verifyOtp/${this.state.email}`);
} else {
console.log("login failed");
window.alert("login failed");
}
} catch (error) {
console.error(error);
}
};
edit: I also tried it in postman and it gives "redirect" as response in postman so the api must be working fine
Your problem is in this line
const result = await response.json();
Your response is ok, everything is ok, but when you try to do response.json() and the response from the request isn't a valid json (maybe just a normal text), it will give you that error.
Because response can be a text or a json, you need to do some checking. Where is how to check if response is a json
This is kind of bad because on every request you will need to do this type of checking (transform it to text, try to parse, bla bla...), so What I recommend it you to use something better than fetch.
Axios is very good because it already do that checking.
For your example:
performLogin = async () => {
var body = {
password: this.state.password,
email: this.state.email
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/authenticate";
try {
const response = await fetch(url, options); // Fetch the resource
const text = await response.text(); // Parse it as text
const data = JSON.parse(text); // Try to parse it as json
// Do your JSON handling here
} catch(err) {
// This probably means your response is text, do you text handling here
}
}

Add parameters to post request using js on client side

I'm developing a "TODO" app using node.js and mongodb.
I'm trying to post a new task from the client but I didn't success to pass parameters to the server and from there to the database.
Client code:
<script>
function addData(item, url) {
var text = document.getElementById("myTask").value;
return fetch('/todos',{
method: 'post',
body: text
}).then(response => response.json())
.then(data => console.log(data));
}
</script>
Server code:
app.post('/todos',(req,res) =>{
console.log("\n\n req.body is: \n\n",req.body);
var todo = new Todo({
text: req.body.text});
todo.save().then((doc) =>{
res.send(doc);
console.log(JSON.stringify(doc,undefined,2));
},(err) =>{
res.status(400).send(err); //400 = unable to connect
console.log("Unable to save todo.\n\n\n" , err);
});
});
And the problem is that the client doesn't send the body to the server,
and the body is null on the server side:
See the logs here
(as you can see: req.body = {})
In the js code, I tried to pass the body parameter but I guess I did something wrong so I want to know the best way to pass parameters back to the server (not only the body but text, time and etc)
Thank in advance,
Sagiv
I think that you are missing something. Try to use name of param
body: JSON.stringify({data: text})
OR
read here Fetch: POST json data
I used this code:
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();
and now I succeeded to pass data to the request.
Thanks everybody

Categories

Resources