I am getting the
following error on
web alert :
SyntaxError: Unexpected token 'B', "Billing ha"... is not valid JSON
and in the terminal it says :
erver has started on port http:
mongodb connected
Error: Request failed with status code 400
at createError (C:\Users\bhide\Desktop\image_gen\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\bhide\Desktop\image_gen\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\bhide\Desktop\image_gen\server\node_modules\axios\lib\adapters\http.js:322:11)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'User-Agent': 'OpenAI/NodeJS/3.3.0',
Authorization: 'Bearer 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',
'Content-Length': 126
},
method: 'post',
data: '{"prompt":"panda mad scientist mixing sparkling chemicals, digital art","n":1,"size":"1024x1024","response_format":"b64_json"}',
url: 'https://api.openai.com/v1/images/generations'
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype] {
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)],
timeout: [Function (anonymous)],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'api.openai.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 10,
connecting: false,
_hadError: false,
_parent: null,
_host: 'api.openai.com',
_readableState: [ReadableState],
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular *1],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: true,
[Symbol(pendingSession)]: null,
[Symbol(async_id_symbol)]: 77,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kSetNoDelay)]: false,
[Symbol(kSetKeepAlive)]: true,
[Symbol(kSetKeepAliveInitialDelay)]: 60,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object],
[Symbol(RequestTimeout)]: undefined
},
_header: 'POST /v1/images/generations HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: application/json\r\n' +
'User-Agent: OpenAI/NodeJS/3.3.0\r\n' +
'Authorization: Bearer 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\r\n' +
'Content-Length: 126\r\n' +
'Host: api.openai.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object: null prototype],
requests: [Object: null prototype] {},
sockets: [Object: null prototype],
freeSockets: [Object: null prototype] {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 1,
maxCachedSessions: 100,
_sessionCache: [Object],
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/v1/images/generations',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 4,
_maxListeners: undefined,
socket: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
rawHeaders: [Array],
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 400,
statusMessage: 'Bad Request',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular *1],
responseUrl: 'https://api.openai.com/v1/images/generations',
redirects: [],
[Symbol(kCapture)]: false,
[Symbol(kHeaders)]: [Object],
[Symbol(kHeadersCount)]: 28,
[Symbol(kTrailers)]: null,
[Symbol(kTrailersCount)]: 0,
[Symbol(RequestTimeout)]: undefined
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'api.openai.com',
protocol: 'https:',
_redirectable: Writable {
_writableState: [WritableState],
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 126,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: 'https://api.openai.com/v1/images/generations',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'content-type': [Array],
'user-agent': [Array],
authorization: [Array],
'content-length': [Array],
host: [Array]
},
[Symbol(kUniqueHeaders)]: null
},
response: {
status: 400,
statusText: 'Bad Request',
headers: {
date: 'Sun, 06 Aug 2023 18:22:47 GMT',
'content-type': 'application/json',
'content-length': '172',
connection: 'close',
'access-control-allow-origin': '*',
'openai-version': '2020-10-01',
'openai-organization': 'user-gdyfvrcwjmqck8ksjfdryszg',
'x-request-id': 'c6fda4fc00dcd2aae298db0e1ae5039f',
'openai-processing-ms': '34',
'strict-transport-security': 'max-age=15724800; includeSubDomains',
'cf-cache-status': 'DYNAMIC',
server: 'cloudflare',
'cf-ray': '7f294ea64e751bd9-BOM',
'alt-svc': 'h3=":443"; ma=86400'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
data: '{"prompt":"panda mad scientist mixing sparkling chemicals, digital art","n":1,"size":"1024x1024","response_format":"b64_json"}',
url: 'https://api.openai.com/v1/images/generations'
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: [TLSSocket],
_header: 'POST /v1/images/generations HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: application/json\r\n' +
'User-Agent: OpenAI/NodeJS/3.3.0\r\n' +
'Authorization: Bearer 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\r\n' + 'Content-Length: 126\r\n' +
'Host: api.openai.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/v1/images/generations',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'api.openai.com',
protocol: 'https:',
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype],
[Symbol(kUniqueHeaders)]: null
},
data: { error: [Object] }
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
Error: Request failed with status code 400
at createError (C:\Users\bhide\Desktop\image_gen\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\bhide\Desktop\image_gen\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\bhide\Desktop\image_gen\server\node_modules\axios\lib\adapters\http.js:322:11)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'User-Agent': 'OpenAI/NodeJS/3.3.0',
Authorization: 'Bearer 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',
'Content-Length': 126
},
method: 'post',
data: '{"prompt":"panda mad scientist mixing sparkling chemicals, digital art","n":1,"size":"1024x1024","response_format":"b64_json"}',
url: 'https://api.openai.com/v1/images/generations'
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype] {
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)],
timeout: [Function (anonymous)],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'api.openai.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 10,
connecting: false,
_hadError: false,
_parent: null,
_host: 'api.openai.com',
_readableState: [ReadableState],
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular *1],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: true,
[Symbol(pendingSession)]: null,
[Symbol(async_id_symbol)]: 398,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kSetNoDelay)]: false,
[Symbol(kSetKeepAlive)]: true,
[Symbol(kSetKeepAliveInitialDelay)]: 60,
create.jsx
import React, { useState } from "react";
import FormField from "./components/FormField";
import Loader from "./components/Loader";
import { preview } from "./assets";
import { useNavigate } from "react-router-dom";
import { getRandomPrompt } from "./utils";
function CreatePost() {
const navigate = useNavigate();
const [form, setForm] = useState({ name: "", prompt: "", photo: "" });
const [generatingImg, setGeneratingImg] = useState(false);
const [loading, setLoading] = useState(false);
const generateImg = async () => {
if (form.prompt) {
try {
setGeneratingImg(true);
const response = await fetch("http://localhost:8080/api/v1/ai", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: form.prompt }),
});
const data = await response.json();
setForm({ ...form, photo: `data:image/jpeg;base64,${data.photo}` });
} catch (err) {
alert(err);
} finally {
setGeneratingImg(false);
}
} else {
alert("enter a prompt");
}
};
const handleSubmit = () => {
};
const handleChange = (e) => {
setForm({ ...form, [e.target.name]: e.target.value });
};
const handleSurpriseMe = () => {
const randomPrompt = getRandomPrompt(form.prompt);
setForm({ ...form, prompt: randomPrompt });
};
return (
<section className="max-w-7xl mx-auto">
<div>
<h1 className="font-extrabold text-[#22238] text-[32px]">Create</h1>
<p className="mt-2 text-[#666e75] text-[14px] max-w-[500px]">
Create Imaginative images through this AI tool and share
</p>
</div>
<form className="mt-16 max-2-3xl" onSubmit={handleSubmit}>
<div className="flex flex-col gap-5">
<FormField
LabelName="Your Name"
type="text"
name="name"
placeholder="john"
value={form.name}
handleChange={handleChange}
/>
<FormField
LabelName="prompt"
type="text"
name="prompt"
placeholder="yellow boat"
value={form.prompt}
handleChange={handleChange}
isSurpriseMe
handleSurpriseMe={handleSurpriseMe}
/>
</div>
<div className="relative bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded focus:ring-blue-500 focus:border-blue-500 w-64 p-3 h-64 flex justify-center items-center">
{form.photo ? (
<img
src={form.photo}
alt={form.prompt}
className="w-full h-full object-contain"
/>
) : (
<img
src={preview}
alt="preview"
className="w-9/12 h-9/12 object-contain opacity-40"
/>
)}
<div>
{generatingImg && (
<div className="justify-center items-center absolute inset-0 z-0 bg-[rgba(0,0,0,0.5)]">
<Loader />
</div>
)}
</div>
</div>
<div className="mt-5 flex gap-5">
<button
type="button"
onClick={generateImg}
className="text-white rounded-md bg-green-700 text-sm font-medium w-full sm:w-auto px-6 py-2.5 text-center"
>
{generatingImg ? "Generating.." : "Generate"}
</button>
</div>
<div className="mt-10 text-[#666e75]">
<p>Once you have generated the image you want, you can share it!</p>
<button
type="submit"
className="text-white px-5 py-2.5 rounded-md text-sm bg-[#6469ff]"
>
{loading ? "Sharing" : "Share with Community"}
</button>
</div>
</form>
</section>
);
}
export default CreatePost;
airouts.jsx
import express from "express";
import dotenv from "dotenv";
dotenv.config();
import { Configuration, OpenAIApi } from "openai";
const router = express.Router();
const configuration = new Configuration({ apiKey: process.env.OpenAI_API_KEY });
const openai = new OpenAIApi(configuration);
router.route("/").get((req, res) => {
res.send("hello from tabaya");
});
router.route("/").post(async (req, res) => {
try {
const { prompt } = req.body;
const airesponse = await openai.createImage({
prompt,
n: 1,
size: "1024x1024",
response_format: "b64_json",
});
const image = airesponse.data.data[0].b64_json;
res.status(200).json({ photo: image });
} catch (err) {
console.error(err);
res
.status(500)
.send(err?.response.data.error.message || "Something went wrong");
}
});
export default router;
index.jsx
import express from "express";
import * as dotenv from "dotenv";
import cors from "cors";
import postRoutes from "./routes/postRoutes.js";
import aiRoutes from "./routes/aiRoutes.js"
import connectdb from "./mongodb/connect.js";
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json({ limit: "50mb" }));
app.use('/api/v1/post',postRoutes) ;
app.use('/api/v1/ai',aiRoutes)
app.get("/", async (req, res) => {
res.send("hello from tanaya");
});
const startserver = async () => {
try {
await connectdb(process.env.MONGODB_URL);
app.listen(8080, () =>
console.log("server has started on port http://localhost:8080")
);
} catch (err) {
console.log(err);
}
};
startserver();
What I have tried:
i checked if server is working fine and its endpoints