我正试图将curl
请求转换为axios
请求:
curl请求格式如下:
curl -s -X POST
-d '{"version": "12ac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea", "input": {"prompt": "sunset over a lake in the mountains"}'
-H "Authorization: Token 123123123123123123"
-H 'Content-Type: application/json'
https://api.replicate.com/v1/predictions
下面是我如何将其翻译为axios
请求:
try {
const response = await axios.post(
"https://api.replicate.com/v1/predictions",
'{"version": "12ac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea", "input": {"prompt": "sunset over a lake in the mountains"}',
{
headers: {
Authorization: "Token 123123123123123123",
"Content-Type": "application/json",
},
}
);
console.log("RESPONSE ----->", response);
} catch (err) {
console.info("ERROR---->", err);
}
但是,我一直收到以下错误:
ERROR----> [AxiosError: Request failed with status code 400] {
code: 'ERR_BAD_REQUEST'
代码格式是否正确?
完全错误:
2022-07-04T15:14:47.902Z d13a7d45-eb0b-4365-a721-f06f2f2fc968 INFO ERROR----> [AxiosError: Request failed with status code 400] {
code: 'ERR_BAD_REQUEST',
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,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
Authorization: 'Token 123123123',
'User-Agent': 'axios/0.27.2',
'Content-Length': 150
},
method: 'post',
url: 'https://api.replicate.com/v1/predictions',
data: '"{\"version\": \"2e3975b1692cd6aecac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea\", \"input\": {\"prompt\": \"sunset over a lake in the mountains\"}"'
},
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,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'api.replicate.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 10,
connecting: false,
_hadError: false,
_parent: null,
_host: 'api.replicate.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)]: 6,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object],
[Symbol(RequestTimeout)]: undefined
},
_header: 'POST /v1/predictions HTTP/1.1rn' +
'Accept: application/json, text/plain, */*rn' +
'Content-Type: application/jsonrn' +
'Authorization: Token 123123123123123rn' +
'User-Agent: axios/0.27.2rn' +
'Content-Length: 150rn' +
'Host: api.replicate.comrn' +
'Connection: closern' +
'rn',
_keepAliveTimeout: 0,
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
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/predictions',
_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,
headers: [Object],
rawHeaders: [Array],
trailers: {},
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.replicate.com/v1/predictions',
redirects: [],
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'api.replicate.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: 150,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: 'https://api.replicate.com/v1/predictions',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'content-type': [Array],
authorization: [Array],
'user-agent': [Array],
'content-length': [Array],
host: [Array]
}
},
response: {
status: 400,
statusText: 'Bad Request',
headers: {
date: 'Mon, 04 Jul 2022 15:14:47 GMT',
'content-type': 'application/json',
'content-length': '74',
connection: 'close',
allow: 'GET, POST, HEAD, OPTIONS',
'x-frame-options': 'DENY',
'x-content-type-options': 'nosniff',
'referrer-policy': 'same-origin',
'cross-origin-opener-policy': 'same-origin',
via: '1.1 vegur',
'cf-cache-status': 'DYNAMIC',
'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
'report-to': '{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=BBZ%2FuLKvNnSPD5CiPhRgFwAJA2cjjQUj29MokMhPaNhdRqCr%2Fe4xMan2uLUk2YW3q10spY8wQPnRlmhFUfg6N5t4kLVwBqmKs2UD%2B8Q9Fx7v5zXNpoV%2FkTNRt352MjWtAmKV"}],"group":"cf-nel","max_age":604800}',
nel: '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}',
'strict-transport-security': 'max-age=15552000',
server: 'cloudflare',
'cf-ray': '7258d008fc19823f-IAD'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: [Object],
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'post',
url: 'https://api.replicate.com/v1/predictions',
data: '"{\"version\": \"2e3975b1692cd6aecac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea\", \"input\": {\"prompt\": \"sunset over a lake in the mountains\"}"'
},
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,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [TLSSocket],
_header: 'POST /v1/predictions HTTP/1.1rn' +
'Accept: application/json, text/plain, */*rn' +
'Content-Type: application/jsonrn' +
'Authorization: Token 123123123123123rn' +
'User-Agent: axios/0.27.2rn' +
'Content-Length: 150rn' +
'Host: api.replicate.comrn' +
'Connection: closern' +
'rn',
_keepAliveTimeout: 0,
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/v1/predictions',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'api.replicate.com',
protocol: 'https:',
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
data: { non_field_errors: [Array] }
}
}
您忘记了Authorization
头中的Token
部分:
Authorization: "123123123123123123"
如果您查看axios调用的响应,您将看到:
data: { detail: 'Authentication credentials were not provided.' }
所以只要更新你的代码并添加Token
:
Authorization: "Token 123123123123123123"
我也认为你的实际数据可能有问题,试着这样发送:
const response = await axios.post(
"https://api.replicate.com/v1/predictions",
{
version: "12ac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea",
input: {
prompt: "sunset over a lake in the mountains"
}
},
{
headers: {
Authorization: "Token 123123123123123123",
"Content-Type": "application/json",
},
}
);
或在发送之前序列化数据:
const data = JSON.stringify({
version: "12ac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea",
input: {
prompt: "sunset over a lake in the mountains"
}
});
const response = await axios.post(
"https://api.replicate.com/v1/predictions", data,
{
headers: {
Authorization: "Token 123123123123123123",
"Content-Type": "application/json",
},
}
);
正如您在错误消息中看到的那样,数据正在被转义,所以这可能是问题所在:
data: '"{\"version\": \"2e3975b1692cd6aecac28616dba364cc9f1e30c610c6efd62dbe9b9c7d1d03ea\", \"input\": {\"prompt\": \"sunset over a lake in the mountains\"}"'