Nightelf9
CDCloudflare Developers
•Created by Nightelf9 on 3/2/2024 in #pages-help
how to query DB from frontend using pages and D1
I've successfully been able to GET pre defined static data from my D1 database (by using the generic js code) but I'm not able to query the DB by sending a search string into the js DB function code. here are my 2 js codes
javascript.js
async function searchCustomers() {
const companyNameInput = document.getElementById('companyNameInput').value;
console.log('Input value:', companyNameInput); // Log the input value to the console
const response = await fetch('getDB', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ companyName: companyNameInput }),
});
const data = await response.json();
// Handle the data or update the resultsContainer as needed
document.getElementById('resultsContainer').innerHTML = JSON.stringify(data);
}
async function fetchData() {
try {
const response = await fetch('DB', {
method: 'GET',
headers: {
'Accept': 'application/json'
}
});
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error fetching data:', error.message);
}
}
// Call fetchData to initiate the process
fetchData();
getDB.js
export async function onRequest(context, request) {
const companyName = request.json.companyName;
console.log('Received companyName:', companyName); // Log the companyName to the console
const ps = context.env.DB.prepare(
SELECT CompanyName FROM Customers WHERE CompanyName = ?
);
const data = await ps.all(companyName);
return new Response.json(data);
}
the companyName search term doesn't get into the getDB.js function - it says internal error 500
fyi, I'm a novice at cloudflare and coding in general any help will be greatly appreciated 😄2 replies