Somehow the fetch from next13 doesnt work with Django on localhost:8001.
I get the following error:
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:7188:34)
at node:internal/deps/undici/undici:7516:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: Error: [object Object]
at makeNetworkError (node:internal/deps/undici/undici:6317:51)
at httpNetworkFetch (node:internal/deps/undici/undici:7810:16)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async httpNetworkOrCacheFetch (node:internal/deps/undici/undici:7703:33)
at async httpFetch (node:internal/deps/undici/undici:7557:37)
at async schemeFetch (node:internal/deps/undici/undici:7489:18)
at async node:internal/deps/undici/undici:7342:20
at async mainFetch (node:internal/deps/undici/undici:7338:20) {
[cause]: undefined
}
}
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:7188:34)
at node:internal/deps/undici/undici:7516:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
digest: '1117663215'
with this code:
import './globals.css'
export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
// const data = await fetch(`https://dummyjson.com/products/1`, { cache: 'force-cache' });
const data = await fetch(`http://localhost:8001/board/`, {
method: 'GET', headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
redirect: 'follow',
cache: 'force-cache'
});
console.log(data)
return (
<html lang="en">
<head />
<body>
<h1></h1>
<div>{children}</div>
</body>
</html>
)
}
Fetching from any other public api works. CORS is enabled and CORS_ORIGIN_ALLOW_ALL = True is set in the Django settings.py
Any idea how I can fix this?
Thanks
Ok I solved it myself
For who are running into the same error here is my solution: you need to replace the localhost with 127.0.0.1
Somehow nextjs doesn't like to fetch data from localhost...
Please find the correct code below:
import './globals.css'
export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
// const data = await fetch(`https://dummyjson.com/products/1`, { cache: 'force-cache' });
const data = await fetch(`http://127.0.0.1:8001/board/`, {
method: 'GET', headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
redirect: 'follow',
cache: 'force-cache'
});
console.log(data)
return (
<html lang="en">
<head />
<body>
<h1></h1>
<div>{children}</div>
</body>
</html>
)
}
Related
I am using Flutter and Django and have this error when try to call the backend
Back end error :
{detail: Unsupported media type "text/plain; charset=utf-8" in request.}
Flutter code :
Future<void> addAlbum(Album album) async {
print('5');
final url = Uri.parse('http://127.0.0.1:8000/list-create/');
try {
print('6');
final response = await http.post(url,
headers: {
'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f',
},
body: json.encode({
'title': album.title,
'cover': album.cover, // => this is an int
'photos_number': album.photos_number, // => this is an int
}));
print('6 ed');
final responseData = json.decode(response.body);
print(responseData.toString());
final newAlbum = Album(
title: album.title,
cover: album.cover,
photos_number: album.photos_number,
);
print('6 edddgg');
_items.add(newAlbum);
print('6 f');
notifyListeners();
} catch (error) {
print('7');
print(error);
throw error;
}
}
}
Add json content type header.
headers: {
'Authorization': 'Token dc7e96ed776bc44d013b44fdfe560a616c64646f',
'Content-Type': 'application/json; charset=UTF-8',
},
This is my JS code for the API
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
user:user
}),
})
.then((res) => {
return res.json();
})
.catch((err) => {
console.log("Error in getUser: " + err);
});
return json;
};
Here is an attempt to make the request, which unfortunately return the authentication error.
fetchUser.request("kirolosM")
.then((result)=>{
console.log(result);
}).catch((err)=>{console.log("Error ",err);})
The error
{
"message": "Missing Authentication Token"
}
I have tested the API using postman and it is working as expexted.
Probably useful to compare the request sent from your json code to the one you're sending from postman. It looks like you need to include you auth token in your headers in your request.
Something like
export const getUser = async (user) => {
//Working
const json = await fetch( "*****/username/getUser", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authentication": `Bearer ${token}`
},
...
I'm tyring to get a list of all the site collections that users have permissions to access. My plan is to display these on the home page, to make it easy for them to navigate to each of their sites. I've tried the following code, but nothing form my API call is writing the the console. It's just blank. What am I missing with writing to the console? Is the name siteURL wrong?
'''
$.ajax({
url: "/_api/search/query?querytext='contentclass:sts_site'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var results = data.d.results;
var itemhtml = "";
$.each(results, function (index, dataRec) {
console.log(siteUrl);
});
},
error: function (data) {
(data);
}
})
'''
Here is a code snippet to get all site collection and print using Console.log:
<script src="https://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready(function() {
//print sites info
searchSites(_spPageContextInfo.webAbsoluteUrl,
function(query){
var resultsCount = query.PrimaryQueryResult.RelevantResults.RowCount;
for(var i = 0; i < resultsCount;i++) {
var row = query.PrimaryQueryResult.RelevantResults.Table.Rows.results[i];
var siteUrl = row.Cells.results[6].Value;
console.log(JSON.stringify(siteUrl));
}
},
function(error){
console.log(JSON.stringify(error));
}
);
});
function searchSites(webUrl,success, failure) {
var url = webUrl + "/_api/search/query?querytext='contentclass:sts_site'";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d.query);
},
error: function (data) {
failure(data);
}
});
}
</script>
Reference:
What is the REST endpoint URL to get list of site collections?
I am facing an issue of receiving NULL response for the axios POST request I made. How do I correct this error?
I've tried to changing multipart/form-data into x-www-form-urlencoded and multipart/x-www-form-urlencoded
async submitUser() {
this.memberObj = {
id: this.memberObjLocal.id,
name: this.memberObjLocal.name,
password: this.memberObjLocal.password,
email: this.memberObjLocal.email,
password: this.memberObjLocal.password,
gender: this.memberObjLocal.gender,
experience: this.memberObjLocal.experience,
birth: this.memberObjLocal.birth,
phoneNum: this.memberObjLocal.phoneNum,
address: this.address,
introduce: this.introduce,
pic: this.pic
};
const config = {
headers: { "Content-Type": "multipart/form-data" }
};
var formData = new FormData();
for (let data in this.memberObj) {
console.log(data);
formData.append(data, this.memberObj[data]);
console.log(this.memberObj[data]);
}
for (var key of formData.entries()) {
console.log(key[0] + ", " + key[1]);
}
try {
let response = await this.$axios.$post("/users/", formData, config);
this.$router.push("/");
console.log(response) // null
} catch (e) {
console.log(e.response);
}
}
Please try to use like this
import axios from "axios";
//... your codes here
axios({
url: "/users/",
method: "post",
data: formData,
headers: config.headers
})
.then(response => {
this.$router.push("/");
console.log(response);
})
.catch(error => console.error(error));
//... and other codes here
and you can see more examples!
I want to change my current text email format to HTML format, so that I can send an email in nicely formatted way with headers, font values etc as shown in the screenshot below.
Image showing email body with header font size etc
Currently I have text format for sending email using AWS.ses
exports.sendEmail = function(email, token, event, context) {
var ses = new AWS.SES({
region: process.env.SES_REGION
});
var eParams = {
Destination: {
ToAddresses: [email]
},
Message: {
Body: {
Text: {
//template or environment variable
Data: `Hello ${event.request.userAttributes.given_name},\n\nYour Device Validation Token is ${token}\nSimply copy this token and paste it into the device validation input field.`
}
},
Subject: {
//template or environment variable
Data: "CWDS - CARES Device Validation Token"
}
},
//environment variable
Source: process.env.SOURCE_EMAIL
};
/* eslint-disable no-unused-vars */
ses.sendEmail(eParams, function(err, data){
if(err) {
logWrapper.logExceptOnTest("FAILURE SENDING EMAIL - Device Verify OTP");
logWrapper.logExceptOnTest(event);
logWrapper.logExceptOnTest(context);
context.fail(err);
}
else {
logWrapper.logExceptOnTest("Device Verify OTP sent");
context.succeed(event);
}
});
/* eslint-enable no-unused-vars */
}
It's fairly straight forward, just add the Html section of the Body node, i.e.:
var eParams = {
Destination: {
ToAddresses: [email]
},
Message: {
Body: {
Text: {
Data: `Hello ${event.request.userAttributes.given_name},\n\nYour Device Validation Token is ${token}\nSimply copy this token and paste it into the device validation input field.`
},
Html: {
Data: `<html><head><title>Your Token</title><style>h1{color:#f00;}</style></head><body><h1>Hello ${event.request.userAttributes.given_name},</h1><div>Your Device Validation Token is ${token}<br/>Simply copy this token and paste it into the device validation input field.</div></body></html>`
}
},
Subject: {
//template or environment variable
Data: "CWDS - CARES Device Validation Token"
}
},
//environment variable
Source: process.env.SOURCE_EMAIL
};
However... I generally split out the email template into html and text files, and use handlebars to inject data items. Here is an extract of one of my working solutions:
contact/contact.js
var AWS = require('aws-sdk');
var ses = new AWS.SES();
var fs = require('fs');
var Handlebars = require('handlebars');
module.exports.sendemail = (event, context, callback) =>
var eventData = JSON.parse(event.body);
fs.readFile("./contact/emailtemplate.html", function (err, emailHtmlTemplate) {
if (err) {
console.log("Unable to load HTML Template");
throw err;
}
fs.readFile("./contact/emailtemplate.txt", function (err, emailTextTemplate) {
if (err) {
console.log("Unable to load TEXT Template");
throw err;
}
// Prepare data for template placeholders
var emailData = {
"given_name": event.request.userAttributes.given_name,
"token": token
};
// Inject data into templates
var templateTitle = Handlebars.compile(process.env.EMAIL_TITLE);
var titleText = templateTitle(emailData);
console.log(titleText);
emailData.title = titleText;
var templateText = Handlebars.compile(emailTextTemplate.toString());
var bodyText = templateText(emailData);
console.log(bodyText);
var templateHtml = Handlebars.compile(emailHtmlTemplate.toString());
var bodyHtml = templateHtml(emailData);
console.log(bodyHtml);
// Prepare SES params
var params = {
Destination: {
ToAddresses: [
process.env.EMAIL_TO
]
},
Message: {
Body: {
Text: {
Data: bodyText,
Charset: 'UTF-8'
},
Html: {
Data: bodyHtml
},
},
Subject: {
Data: titleText,
Charset: 'UTF-8'
}
},
Source: process.env.EMAIL_FROM
}
console.log(JSON.stringify(params,null,4));
// Send Email
ses.sendEmail(params, function(err,data){
if(err) {
console.log(err,err.stack); // error
var response = {
statusCode: 500,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
},
body: JSON.stringify({"message":"Error: Unable to Send Message"})
}
callback(null, response);
}
else {
console.log(data); // success
var response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
},
body: JSON.stringify({"message":"Message Sent"})
}
callback(null, response);
}
});
}); //end of load text template
}); //end of load html template
};
contact/emailtemplate.html
<!DOCTYPE html>
<html>
<head>
<title>Your New Token</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
h1 { color:#f00; }
</style>
</head>
<body>
<div class="emailwrapper">
<div class="main">
<div class="content">
<h1>Hi {{given_name}}</h1>
<div style="padding:20px;">
<div>your new token is {{token}}.</div>
</div>
</div>
</div>
</div>
</body>
</html>
contact/emailtemplate.txt
Hi {{given_name}}
your new token is {{token}}.