const getPrinter_material = (printer_id, response) => {
pool.query(`SELECT pr.printer_id, m.material
FROM printer_material pm
JOIN printer pr ON pm.printer_id = pr.printer_id
JOIN material m ON pm.material_id = m.material_id
WHERE pr.printer_id = ${printer_id};`, (error, results) => {
if (error) {
throw error;
}
response.status(200).json(results.rows);
});
};
printer_id
получаю я её вот таким образомconst postPrinterData = (request, response) => {
const printer_id = parseInt(request.body.printer_id, 10);
// Выполнить нужные действия с полученным printerId
console.log('Получен printer_id:', printer_id);
// Отправка printer_id для GET-запроса
getPrinter_material(printer_id, response);
};
printer_id
передаётся число, а не строка. То есть я уверен, что я не правильно использую константу printer_id
, т.к у меня выдаёт ошибку ошибка синтаксиса (примерное положение: "[")
и эта ошибка указывает на строку throw error;
SELECT pr.printer_id, m.material
FROM printer_material pm
JOIN printer pr ON pm.printer_id = pr.printer_id
JOIN material m ON pm.material_id = m.material_id
WHERE pr.printer_id = значение;
error: ошибка синтаксиса (примерное положение: "[")
at Parser.parseErrorMessage (/var/www/html/test_aria/api/node_modules/pg-protocol/dist/parser.js:287:98)
at Parser.handlePacket (/var/www/html/test_aria/api/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/var/www/html/test_aria/api/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/var/www/html/test_aria/api/node_modules/pg-protocol/dist/index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:324:12)
at readableAddChunk (node:internal/streams/readable:297:9)
at Readable.push (node:internal/streams/readable:234:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
length: 149,
severity: 'ОШИБКА',
code: '42601',
detail: undefined,
hint: undefined,
position: '188',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1188',
routine: 'scanner_yyerror'
}
const query = {
`text: SELECT pr.printer_id, m.material
FROM printer_material pm
JOIN printer pr ON pm.printer_id = pr.printer_id
JOIN material m ON pm.material_id = m.material_id
WHERE pr.printer_id = $1,
values: [printer_id],`
};
const query = {
text: `SELECT pr.printer_id, m.material
FROM printer_material pm
JOIN printer pr ON pm.printer_id = pr.printer_id
JOIN material m ON pm.material_id = m.material_id
WHERE pr.printer_id = $1,
values: [printer_id],`
};
const text = 'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *'
const values = ['brianc', 'brian.m.carlson@gmail.com']
const res = await client.query(text, values)
const query = {
text: 'INSERT INTO users(name, email) VALUES($1, $2)',
values: ['brianc', 'brian.m.carlson@gmail.com'],
}
const res = await client.query(query)
console.log(res.rows[0])
"number"
. Но может да и ты прав хз. const query = {
text: 'INSERT INTO users(name, email) VALUES($1, $2)',
values: ['brianc', 'brian.m.carlson@gmail.com'],
}
const res = await client.query(query)
console.log(res.rows[0])
const getPrinter_material = (printer_id, response) => {
const query = {
text: 'SELECT pr.printer_id, m.material FROM printer_material pm JOIN printer pr ON pm.printer_id = pr.printer_id JOIN material m ON pm.material_id = m.material_id WHERE pr.printer_id = $1;',
values: [printer_id],
}
pool.query(query, (error, results) => {
if (error) {
throw error;
}
response.status(200).json(results.rows);
});
};
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Socket'
| property 'parser' -> object with constructor 'HTTPParser'
--- property 'socket' closes the circl
и это сдец const getPrinter_material = (printer_id, response) => {
const query = {
text: 'SELECT pr.printer_id, m.material FROM printer_material pm JOIN printer pr ON pm.printer_id = pr.printer_id JOIN material m ON pm.material_id = m.material_id WHERE pr.printer_id = $1;',
values: [printer_id],
}
pool.query(query, (error, results) => {
if (error) {
throw error;
}
response.status(200).json([...results.rows]);
});
};
throw new Error('Release called on client which has already been released to the pool.')
console.log(results);
на есть ли результат в принципе, console.log(JSON.stringify(results));
на можно ли представить результат в виде JSON.Result {
command: 'SELECT',
rowCount: 4,
oid: null,
rows: [
{ printer_id: 3, material: '610*175m' },
{ printer_id: 3, material: '610*50m' },
{ printer_id: 3, material: 'A3' },
{ printer_id: 3, material: 'A4' }
],
fields: [
Field {
name: 'printer_id',
tableID: 23183,
columnID: 1,
dataTypeID: 23,
dataTypeSize: 4,
dataTypeModifier: -1,
format: 'text'
},
Field {
name: 'material',
tableID: 23197,
columnID: 2,
dataTypeID: 1043,
dataTypeSize: -1,
dataTypeModifier: 54,
format: 'text'
}
],
_parsers: [ [Function: parseInteger], [Function: noParse] ],
_types: TypeOverrides {
_types: {
getTypeParser: [Function: getTypeParser],
setTypeParser: [Function: setTypeParser],
arrayParser: [Object],
builtins: [Object]
},
text: {},
binary: {}
},
RowCtor: null,
rowAsArray: false,
_prebuiltEmptyResultObject: { printer_id: null, material: null }
}
{"command":"SELECT","rowCount":4,"oid":null,"rows":[{"printer_id":3,"material":"610*175m"},{"printer_id":3,"material":"610*50m"},{"printer_id":3,"material":"A3"},{"printer_id":3,"material":"A4"}],"fields":[{"name":"printer_id","tableID":23183,"columnID":1,"dataTypeID":23,"dataTypeSize":4,"dataTypeModifier":-1,"format":"text"},{"name":"material","tableID":23197,"columnID":2,"dataTypeID":1043,"dataTypeSize":-1,"dataTypeModifier":54,"format":"text"}],"_parsers":[null,null],"_types":{"_types":{"arrayParser":{},"builtins":{"BOOL":16,"BYTEA":17,"CHAR":18,"INT8":20,"INT2":21,"INT4":23,"REGPROC":24,"TEXT":25,"OID":26,"TID":27,"XID":28,"CID":29,"JSON":114,"XML":142,"PG_NODE_TREE":194,"SMGR":210,"PATH":602,"POLYGON":604,"CIDR":650,"FLOAT4":700,"FLOAT8":701,"ABSTIME":702,"RELTIME":703,"TINTERVAL":704,"CIRCLE":718,"MACADDR8":774,"MONEY":790,"MACADDR":829,"INET":869,"ACLITEM":1033,"BPCHAR":1042,"VARCHAR":1043,"DATE":1082,"TIME":1083,"TIMESTAMP":1114,"TIMESTAMPTZ":1184,"INTERVAL":1186,"TIMETZ":1266,"BIT":1560,"VARBIT":1562,"NUMERIC":1700,"REFCURSOR":1790,"REGPROCEDURE":2202,"REGOPER":2203,"REGOPERATOR":2204,"REGCLASS":2205,"REGTYPE":2206,"UUID":2950,"TXID_SNAPSHOT":2970,"PG_LSN":3220,"PG_NDISTINCT":3361,"PG_DEPENDENCIES":3402,"TSVECTOR":3614,"TSQUERY":3615,"GTSVECTOR":3642,"REGCONFIG":3734,"REGDICTIONARY":3769,"JSONB":3802,"REGNAMESPACE":4089,"REGROLE":4096}},"text":{},"binary":{}},"RowCtor":null,"rowAsArray":false,"_prebuiltEmptyResultObject":{"printer_id":null,"material":null}}
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Socket'
| property 'parser' -> object with constructor 'HTTPParser'
--- property 'socket' closes the circle
response.status(200).json({result: 'ok'});
const getPrinter_material = (printer_id, response) => {
pool.connect((error, client, release) => {
if (error) {
throw error;
}
const query = {
text: 'SELECT pr.printer_id, m.material FROM printer_material pm JOIN printer pr ON pm.printer_id = pr.printer_id JOIN material m ON pm.material_id = m.material_id WHERE pr.printer_id = $1;',
values: [printer_id],
}
client.query(query, (error, results) => {
release();
if (error) {
throw error;
}
// Добавленный код
response.status(200).json({result: 'ok'});
});
});
};
Страница не найдена
и в консоле тоже самое TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Socket'
| property 'parser' -> object with constructor 'HTTPParser'
--- property 'socket' closes the circle
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Socket'
| property 'parser' -> object with constructor 'HTTPParser'
--- property 'socket' closes the circle
)function loadSelectOptions2(url, selectElement) {
fetch(url)
.then(response => response.json())
.then(data => {
data.forEach(item => {
const option = createOption(item.printer_id, item.material);
selectElement.appendChild(option);
});
})
.catch(error => {
console.error(error);
// Обработать ошибку
});
}
selectElement2.addEventListener('change', () => {
const selectedPrinterId = selectElement2.value;
console.log('selectedPrinterId:', selectedPrinterId);
// Очистить select3 перед загрузкой новых опций
selectElement3.innerHTML = '';
// Загрузить опции для select3 на основе выбранного значения select2
if (selectedPrinterId) {
const url = `http://:3000/printer_material?printer_id=${encodeURIComponent(selectedPrinterId)}`;
loadSelectOptions2(url, selectElement3);
}
});
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const db = require('./pool');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(cors());
app.get('/printer_material', (req, res) => {
const printer_id = parseInt(req.query.printer_id, 10);
console.log('Received printer_id:', printer_id); // Вывод значения в консоль как число
db.getPrinter_material(printer_id, res);
});
http.createServer(app).listen(port, () => {
console.log(`App running on port ${port}.`);
});
//pool.js
const { response } = require('express');
const Pool = require('pg').Pool;
const pool = new Pool({
user: '',
host: '',
database: '',
password: '',
port: 5432,
});
const getPrinter_material = (printer_id, response) => {
console.log('Received printer_id:', printer_id);
pool.connect((error, client, release) => {
if (error) {
throw error;
}
const query = {
text: `SELECT pr.printer_id, m.material FROM printer_material pm JOIN printer pr ON pm.printer_id = pr.printer_id JOIN material m ON pm.material_id = m.material_id WHERE pr.printer_id = $1`,
values: [printer_id],
};
console.log('Query text:', query.text);
client.query(query, (error, results) => {
release();
if (error) {
throw error;
}
console.log(results.rows);
response.json(results.rows);
});
});
};
module.exports = {
getPrinter_material,
};
console.log
пока они остались так как я часть за частью проверял работоспособность кода