Код: Выделить всё
{
"error": "415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
}
Код: Выделить всё
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import pyodbc
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
# Database connection setup
SERVER = 'maidsqlppserver.database.windows.net'
DATABASE = 'miadsqlpp'
USERNAME = 'ysadmin'
PASSWORD = 'yellowsense@1234'
connectionString = f'DRIVER={{ODBC Driver 18 for SQL Server}};SERVER={SERVER};DATABASE={DATABASE};UID={USERNAME};PWD={PASSWORD}'
try:
conn = pyodbc.connect(connectionString)
cursor = conn.cursor()
except pyodbc.Error as e:
print("Error connecting to the database:", e)
# Function to add custom headers to every response
@app.after_request
def add_headers(response):
response.headers['Access-Control-Allow-Origin'] = 'https://yellowsense.in' # Replace with your frontend domain
response.headers['Access-Control-Allow-Methods'] = 'GET, POST' # You can specify the allowed methods
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' # You can specify the allowed headers
return response
@app.route('/society_names', methods=['GET'])
@cross_origin()
def get_society_names():
try:
# Execute a SQL query to retrieve society names and IDs
cursor.execute("SELECT society_id, society_name FROM Society")
rows = cursor.fetchall()
# Convert the result into an array of dictionaries with id and name
society_data = [{"id": row.society_id, "name": row.society_name} for row in rows]
return jsonify(society_data) # Return JSON with id and name
except pyodbc.Error as e:
return jsonify({"error": str(e)})
@app.route('/insert_maid', methods=['POST'])
@cross_origin()
def insert_maid():
try:
data = request.get_json()
aadhar_number = data.get('aadhar_number')
name = data.get('name')
phone_number = data.get('phone_number')
gender = data.get('gender')
services = data.get('services')
locations = data.get('locations')
timings = data.get('timings')
cursor = conn.cursor()
cursor.execute(
"EXEC InsertMaidRegistration ?, ?, ?, ?, ?, ?, ?",
(aadhar_number, name, phone_number, gender, services, locations, timings)
)
conn.commit()
cursor.close()
return jsonify({"message": "Maid entry added successfully"})
except Exception as e:
return jsonify({"error": str(e})
if __name__ == '__main__':
app.run(debug=True)
Код: Выделить всё
Register a Worker
Add Apartment
Additional Information
Name:
Aadhar Number:
Mobile Number:
Gender:
Male
Female
Services:
Maid
Nanny
Cook
Book Slots and Submit Form
Код: Выделить всё
const slotsContainer = document.getElementById("slots");
const tagInput = document.getElementById("tag-input");
const addTagButton = document.getElementById("add-tag");
const submitButton = document.getElementById("submit-button");
const startTime = 6; // Start time (6:00 AM)
const endTime = 30; // End time (6:00 AM of the next day)
const timeSlots = [];
const selectedTimeSlots = [];
const selectedTags = [];
// Generate time slots with 1-hour intervals
for (let i = startTime; i < endTime; i++) {
const slotStartTime = i % 24;
const slotEndTime = (i + 1) % 24;
const slotLabel = `${slotStartTime.toString().padStart(2, '0')}:00 - ${slotEndTime.toString().padStart(2, '0')}:00`;
timeSlots.push(slotLabel);
}
timeSlots.forEach((slot) => {
const slotElement = document.createElement("div");
slotElement.classList.add("slot");
slotElement.textContent = slot;
slotElement.addEventListener("click", () => {
slotElement.classList.toggle("selected");
if (slotElement.classList.contains("selected")) {
selectedTimeSlots.push(slot);
} else {
selectedTimeSlots = selectedTimeSlots.filter((time) => time !== slot);
}
});
slotsContainer.appendChild(slotElement);
});
// Predefined tags
const predefinedTags = ["RPH", "SOMU SONNET", "PFR", "AS"];
function displayTags() {
const searchTagsContainer = document.querySelector(".search-tags");
searchTagsContainer.innerHTML = "";
selectedTags.forEach((tag) => {
const tagSpan = document.createElement("span");
tagSpan.textContent = tag;
tagSpan.addEventListener("click", () => {
// Remove the tag when clicked
selectedTags.splice(selectedTags.indexOf(tag), 1);
displayTags();
});
searchTagsContainer.appendChild(tagSpan);
});
}
// Function to populate the datalist with predefined tags
function populateDatalist() {
const datalist = document.getElementById("tags-list");
datalist.innerHTML = "";
predefinedTags.forEach((tag) => {
const option = document.createElement("option");
option.value = tag;
datalist.appendChild(option);
});
}
// Display predefined tags in the datalist
populateDatalist();
addTagButton.addEventListener("click", () => {
const tag = tagInput.value.trim();
if (tag !== "" && !selectedTags.includes(tag)) {
selectedTags.push(tag);
tagInput.value = "";
displayTags();
}
});
submitButton.addEventListener("click", () => {
// Prepare the data to send
const name = document.getElementById("name").value;
const aadhar = document.getElementById("aadhar").value;
const mobile = document.getElementById("mobile").value;
const gender = document.querySelector('input[name="gender"]:checked').value;
const services = [...document.querySelectorAll('input[name="services"]:checked')].map((checkbox) => checkbox.value);
const data = {
aadhar_number: aadhar,
name: name,
phone_number: mobile,
gender: gender,
services: services.join(', '),
locations: selectedTags.join(', '),
timings: selectedTimeSlots.join(', '),
};
// Send the data to the specified form URL
sendDataToFormester(data);
});
function sendDataToFormester(data) {
const formesterFormUrl = 'https://yellowsensebackendapi.azurewebsites.net/insert_maid';
fetch(formesterFormUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Set the content type to JSON
},
body: JSON.stringify(data), // Convert data to a JSON string
})
.then(() => {
alert('Data submitted successfully to YellowSense.');
})
.catch((error) => {
console.error('Error:', error);
alert('An error occurred while submitting data.');
});
}
[img]https://i.stack.imgur. com/8dsLh.png[/img]
Подробнее здесь: https://stackoverflow.com/questions/774 ... ta-because